PHP 将周数和年份转换回 Carbon?
PHP convert week number and year back to Carbon?
我对周数和年份使用 W-Y 格式。
例如2018 年的最后一周将表示为 '52-2018'
.
但我无法让 Carbon 或 DateTime 将其转换回来。
>>> Carbon::createFromFormat('W-Y', '01-2018')
InvalidArgumentException with message 'The format separator does not match
The separation symbol could not be found
Trailing data'
不幸的是,DateTime::createFromFormat
(这是 Carbon 的扩展)不支持 W
格式化字符。
解决此问题的最简单方法是创建一个新的 DateTime
(或 Carbon)实例,并使用本机 setISODate
方法设置年和周数:
$str = '01-2018';
list ($week, $year) = explode('-', $str);
$d = new DateTime;
$d->setISODate($year, $week);
我对周数和年份使用 W-Y 格式。
例如2018 年的最后一周将表示为 '52-2018'
.
但我无法让 Carbon 或 DateTime 将其转换回来。
>>> Carbon::createFromFormat('W-Y', '01-2018')
InvalidArgumentException with message 'The format separator does not match
The separation symbol could not be found
Trailing data'
DateTime::createFromFormat
(这是 Carbon 的扩展)不支持 W
格式化字符。
解决此问题的最简单方法是创建一个新的 DateTime
(或 Carbon)实例,并使用本机 setISODate
方法设置年和周数:
$str = '01-2018';
list ($week, $year) = explode('-', $str);
$d = new DateTime;
$d->setISODate($year, $week);