Why does this date function only work until December 30, 2016?

I have this code:

for ($i=1; $i<=12; $i++) {

    $monthNum  = $i;
    $monthName = date('F', mktime(0, 0, 0, $monthNum, 10));

    $date_established = strtotime($monthName);
    $date_established = strtotime('first day of this month', $date_established);
    $date_established = date('Y-m-d', $date_established);
    $date_established_end = date("Y-m-t", strtotime($date_established));

    echo $i .'::'. $monthName . '::' . $date_established . '::' . $date_established_end . '<br>';

}

and still he produces:

1::January::2016-01-01::2016-01-31
2::February::2016-02-01::2016-02-28
3::March::2016-03-01::2016-03-31
4::April::2016-04-01::2016-04-30
5::May::2016-05-01::2016-05-31
6::June::2016-06-01::2016-06-30
7::July::2016-07-01::2016-07-31
8::August::2016-08-01::2016-08-31
9::September::2016-09-01::2016-09-30
10::October::2016-10-01::2016-10-31
11::November::2016-11-01::2016-11-30
12::December::2016-12-01::2016-12-31

but today (December 31, 2016) everything is spoiled as follows:

1::January::2016-01-01::2016-01-31
2::February::2016-03-01::2016-03-31 
3::March::2016-03-01::2016-03-31 << duplicate
4::April::2016-05-01::2016-05-31
5::May::2016-05-01::2016-05-31 << duplicate
6::June::2016-07-01::2016-07-31
7::July::2016-07-01::2016-07-31 << duplicate
8::August::2016-08-01::2016-08-31
9::September::2016-10-01::2016-10-31
10::October::2016-10-01::2016-10-31 << duplicate
11::November::2016-12-01::2016-12-31
12::December::2016-12-01::2016-12-31 << duplicate

What happened since December 31, 2016? why is my code messed up? thank.

+4
source share
2 answers

Your code crashes in the following lines:

$february = strtotime('February');
echo date(DATE_ISO8601, $february);

which today, December 30, 2016 issues:

2016-03-01T00:00:00+0000

Hmmm ... why does PHP say that "February" is "2016-03-01"? Well, this is due to how PHP fills in the gaps in the missing information: in the absence of explicit absolute time values, PHP uses the current date and time values.

, 30 13:29 , :

strtotime('February');                       // you asked for
strtotime('February 30, 2016 13:29:47 EST'); // PHP interprets as
//                  ^^^^^^^^^^^^^^^^^^^^^ filled in from current time

, . PHP ( , ) , , 30 = 29 + 1 = 1 . ( , - , 2017, PHP 30 = 28 + 2 = 2 , "2017-03-02T00: 00: 00 + 0000"!)

, , , PHP . , strtotime('February'); :

$year = date('Y');
$date_established = strtotime("$monthName 1, $year");

( . : PHP .)

: , "", . , strtotime, , , .

+6

, , :

for ($i=1; $i<=12; $i++) {

    $monthNum  = sprintf("%02d", $i);
    $monthName = date('F', mktime(0, 0, 0, $monthNum, 10));

    $date_established = date("Y-$monthNum-01");
    $date_established_end = date("Y-m-t", strtotime($date_established));

    echo "$i :: $monthName :: $date_established :: $date_established_end <br>\n";

}

, "01", .

: , - , !

+1

Source: https://habr.com/ru/post/1665359/


All Articles