Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime('first day of April') returns same as DateTime('first day of May')

Tags:

php

datetime

April ant May returns same date in php:

var_dump(new DateTime('first day of April')); - '2016-05-01 00:00:00'

var_dump(new DateTime('first day of May')); - '2016-05-01 00:00:00'

Works great for other months, but for April it returns 05 instead of 04.

Edit: 'timezone' => 'Europe/Paris'

Edit2: http://imgur.com/TccRcMo

like image 240
Edgar Avatar asked Mar 31 '16 06:03

Edgar


People also ask

How do you get the first day of the month in PHP?

$first_day = date('Y-m-01'); $last_day = date('Y-m-t'); Php Get First Day Of Month.

How can get first and last day of month in PHP?

We will use date() and strtotime() function to get the last day of the month. Used PHP functions: date() function: Format a local time/date.


1 Answers

This is a very strange behavior, but I found some solutions to get the expected results. The reason why this is not working is the missing year on the DateTime object.

solution #1 (https://3v4l.org/hIA89)

<?php
    $datetime = new DateTime('2016-01-01', new DateTimeZone('Europe/Paris'));
    var_dump($datetime->modify('first day of april'));
    var_dump($datetime->modify('first day of may'));
?>

solution #2 (https://3v4l.org/PDXM3)

<?php
    var_dump(new DateTime('first day of april 2016', new DateTimeZone('Europe/Paris')));
    var_dump(new DateTime('first day of may 2016', new DateTimeZone('Europe/Paris')));
?>

solution #3 (https://3v4l.org/pBH0n)

<?php
    var_dump(new DateTime('1 april', new DateTimeZone('Europe/Paris')));
    var_dump(new DateTime('1st april', new DateTimeZone('Europe/Paris')));
    var_dump(new DateTime('1 may', new DateTimeZone('Europe/Paris')));
    var_dump(new DateTime('1st may', new DateTimeZone('Europe/Paris')));
?>

thx to @Glavic

like image 76
Sebastian Brosch Avatar answered Oct 31 '22 02:10

Sebastian Brosch