How to get the first day of the current year?

后端 未结 11 1819
再見小時候
再見小時候 2020-12-09 14:48

I need to use PHP DateTime to get the first day of the current year. I\'ve tried:

$year = new DateTime(\'first day of this year\');
var_dump($year);
<         


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 15:03

    Just wanted to record some nuance with the answer by lorem monkey

    The suggested method might cause issues with when using time zones.

    scenario: consider current system time is 2018-01-01 00:20:00 UTC and system default time zone is set to UTC.

    date('Y') will give you 2018

    if you are doing something like:

    $startDate = new DateTime('first day of january '.date('Y'), new DateTimeZone('America/New_York'));
    

    This will compute to 'first day of january 2018' but you actually needed the first date of your current year in America/New_York, which is still 2017.

    Stop dropping the ball man, its not new year yet!

    So it is better to just do

    $startDate = new DateTime('first day of january', new DateTimeZone('America/New_York'));
    

    And then do the modifications as needed by using the DateTime::modify() function.

    Relative date formats are fun.

    My scenario: I wanted to get the bounds of this year as in 2018-01-01 00:00:00 to 2018-12-31 23:59:59

    This can be achieved in two ways with relative date formats.

    one way is to use the DateTime::modify() function on the object.

    $startDate = (new DateTime('now', new DateTimeZone("America/New_York")));
    $endDate = (new DateTime('now', new DateTimeZone("America/New_York")));
    
    $startDate->modify("january")
        ->modify("first day of this month")
        ->modify("midnight");
        
    $endDate->modify("next year")
        ->modify("january")
        ->modify("first day of this month")
        ->modify("midnight")->modify("-1 second");
    
    var_dump([$startDate, $endDate]);
    

    Try out here: https://www.tehplayground.com/Qk3SkcrCDkNJoLK2

    Another way to do this is to separate the relative strings with a comma like so:

    $startDate = (new DateTime('first day of january', new DateTimeZone("America/New_York")));
    $endDate = (new DateTime('next year, first day of january, -1 second', new DateTimeZone("America/New_York")));
    var_dump([$startDate, $endDate]);
    

    Try out here: https://www.tehplayground.com/hyCqXLRBlhJbCyks

提交回复
热议问题