Search code examples
phpphp-carbon

PHP and Carbon: How to get a relative time in a different year


I can use this, new \Carbon\Carbon('last sun of September'), to get the last Sunday in September this year. But what if I want the last Sunday in September last year?

I tried both of these:

new \Carbon\Carbon('last sun of September last year')
new \Carbon\Carbon('last year last sun of September')

Both both gave the DD/MM of the last Sunday THIS year, and changed the YYYY to last year.


Solution

  • This seems to only be possible in 2 steps. Either of these work for me:

    $lastYear = (new \DateTime('last year'))->format('Y');
    $dt = new \DateTime('last sun of September ' . $lastYear);
    
    $dt2 = new \DateTime('last year');
    $dt2->modify('last sun of September');
    
    var_dump($dt); // 2017-09-24 00:00:00.000000
    var_dump($dt2); // 2017-09-24 00:00:00.000000
    

    Personally I think the second approach is cleaner.

    I tested it with DateTime, as Carbon is just an extension for that and internally uses the PHP DateTime parser. See also http://php.net/manual/en/datetime.formats.relative.php