Reputation: 3113
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'
Upvotes: 3
Views: 2227
Reputation: 7703
A string of the form '01-2018' can also be converted to '2018W01' with preg_replace
, which can then be processed directly by DateTime
and Carbon.
$str = '01-2018';
$dateTime = new DateTime(preg_replace('~^(\d\d)-(\d\d\d\d)$~','$2W$1',$str));
While with the accepted solution we always get the current time for the date, here it is always 00:00:00.
Demo: https://3v4l.org/mo6dQ
Upvotes: 0
Reputation: 17434
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);
Upvotes: 8