如何在PHP中以特定格式显示今天的下3个日期?

问题描述:

I am trying to print out the next 3 days from today. This code works fine but I need the dates to be in this format "2018 Sept, 29". Changing format keeps giving me errors.

<?php
// Set timezone
date_default_timezone_set('AFRICA/LAGOS');

// Start date
$date = date('Y-m-d');
// End date
$end_date = date('Y-m-d', strtotime("+3 days"));

while (strtotime($date) <= strtotime($end_date)) {
    $date=DateTime::createFromFormat('Y-m-d', $date)->modify('+1 day')->format('Y-m-d');
    echo $date.', ';
}
echo "<br><br>";
?>

You can easily do it with date() and for() loop:-

<?php

date_default_timezone_set('AFRICA/LAGOS');

$date = date('Y-m-d');
for($i =1;$i<=3;$i++){
  echo $end_date = date('Y M,d', strtotime("+$i days"));
  echo PHP_EOL;
}

https://3v4l.org/YXZEe

A bit functional approach:

<?php

function getNextDatesFromCurrentDate($how_many_dates){
    date_default_timezone_set('AFRICA/LAGOS');

    for($i =1;$i<=$how_many_dates;$i++){
        echo $end_date = date('Y M,d', strtotime("+$i days"));
        echo PHP_EOL;
    }
}

getNextDatesFromCurrentDate(3);

https://3v4l.org/1vKVA

Have a look at the PHP date format documentation, you can print the name of the month in english with format('Y-F-d')

Or you can make your own function which returns the name of the month with the number you provide.

To add number of dates to particular date. you need to pass two parameters to strtotime() function.

1.number of days

2.starting date

and to format to '2018 sept, 29' you need to give the correct format to date('Y M, d') function.

$start_date = date('Y-m-d');
$dates = collect();
foreach (range(1,3) as $number_of_days) {
    $dates->push(date('Y M, d', strtotime("+$number_of_days days", strtotime($start_date))));
}

Use Carbon library, to Add days
Like , 
$date = Carbon::today();
$nextday = $date->addDay();