Search code examples
phpphp-carbon

PHP convert week number and year back to Carbon?


I'm using format W-Y for weeknumber & year.

e.g. the final week of 2018 would be represented as '52-2018'.

But I can't get Carbon or DateTime to convert it back.

>>> Carbon::createFromFormat('W-Y', '01-2018')

InvalidArgumentException with message 'The format separator does not match
The separation symbol could not be found
Trailing data'

Solution

  • DateTime::createFromFormat (which is what Carbon extends) doesn't support the W formatting character, unfortunately.

    The easiest way to work around this is to create a new DateTime (or Carbon) instance, and use the native setISODate method to set the year and week number:

    $str = '01-2018';
    list ($week, $year) = explode('-', $str);
    $d = new DateTime;
    $d->setISODate($year, $week);
    

    See https://3v4l.org/g33QV