Laravel Carbon 格式错误
Laravel Carbon formatting error
我遇到了一个奇怪的问题。
我在约会时使用 Carbon。我想使用可以正常工作的格式 Y-W(年,周)。
这里我将它存储到数据库中:
$weekDate = Carbon::createFromFormat('d-m-y', "{$key}")->format('Y-W');
DB::table('backorder_voorspelling')->insert([
'artikelcode' => $articlecode,
'week' => $weekDate,
'aantal' => $value,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
数据库记录正确:
{#426 ▼
+"id": 1
+"artikelcode": "articlecode"
+"week": "2017-44"
+"aantal": "6"
+"created_at": "2018-01-18 11:46:45"
+"updated_at": "2018-01-18 11:46:45"
}
稍后我想将 Y-W 转换回碳时间,这告诉我:
我用来创建碳时间的代码:
$startOfWeek = Carbon::createFromFormat('Y-W', $row->week);
格式相同,存储时我使用格式 ('Y-W'),创建 FromFormat 时我使用格式 ('Y-W'),但它不起作用...
我尝试将 - 替换为 / 但这 returns 同样的错误。
感谢任何帮助。
并非所有日期格式字符都可以在 DateTime::createFromFormat
中使用(这是 Carbon 的扩展)。不幸的是,W
是缺失的之一。
来自the manual:
The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.
您可以通过在新的 DateTime(或 Carbon)实例上手动调用 setISODate
来解决此问题:
list ($year, $week) = explode('-', '2017-44');
$d = new DateTime;
$d->setISODate($year, $week);
setISODate
还接受第三个 $day
参数 - 默认情况下它将设置为一周的第一天,我认为这就是您想要的。
我遇到了一个奇怪的问题。
我在约会时使用 Carbon。我想使用可以正常工作的格式 Y-W(年,周)。 这里我将它存储到数据库中:
$weekDate = Carbon::createFromFormat('d-m-y', "{$key}")->format('Y-W');
DB::table('backorder_voorspelling')->insert([
'artikelcode' => $articlecode,
'week' => $weekDate,
'aantal' => $value,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
数据库记录正确:
{#426 ▼
+"id": 1
+"artikelcode": "articlecode"
+"week": "2017-44"
+"aantal": "6"
+"created_at": "2018-01-18 11:46:45"
+"updated_at": "2018-01-18 11:46:45"
}
稍后我想将 Y-W 转换回碳时间,这告诉我:
我用来创建碳时间的代码:
$startOfWeek = Carbon::createFromFormat('Y-W', $row->week);
格式相同,存储时我使用格式 ('Y-W'),创建 FromFormat 时我使用格式 ('Y-W'),但它不起作用...
我尝试将 - 替换为 / 但这 returns 同样的错误。
感谢任何帮助。
并非所有日期格式字符都可以在 DateTime::createFromFormat
中使用(这是 Carbon 的扩展)。不幸的是,W
是缺失的之一。
来自the manual:
The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.
您可以通过在新的 DateTime(或 Carbon)实例上手动调用 setISODate
来解决此问题:
list ($year, $week) = explode('-', '2017-44');
$d = new DateTime;
$d->setISODate($year, $week);
setISODate
还接受第三个 $day
参数 - 默认情况下它将设置为一周的第一天,我认为这就是您想要的。