PHP 日期转换 YYMMDD 到 yyyy-mm-dd
PHP Date Conversion YYMMDD to yyyy-mm-dd
您好,我正在努力转换字符串:
$file = '150220';
转换为 mysql 日期格式。
我试过了
$newDate = date("Y-m-d", strtotime($file));
但是 returns 之后的 2015-02-24(24 是今天的日期)
参见:http://php.net/manual/en/datetime.createfromformat.php
所以你可以使用这个:
$dateTime = DateTime::createFromFormat('ymd', $file);
$newDate = $dateTime->format('Y-m-d');
strtotime
是一个很棒的函数。它在您提供 YYYY-MM-DD 格式但不使用 YY-MM-DD 时有效。
编辑:如评论中所述,您必须 "turn the string into a valid ISO8601 Notations format by prepending '20' - this is understood by strtotime as specified in the docs "
这将适用于未来 85 年的 64 位系统(直到 2038 年适用于 32 位系统)
$file = '150220';
$newDate = date("Y-m-d", strtotime("20$file"));
您必须小心使用 strtotime,因为它 returns 错误时会导致 date
使用今天的日期。
编辑:如果你想 -1 :首先,这段代码有效,它解释了为什么 op 的代码不起作用,然后考虑使用 "Add comment" 按钮。谢谢
您好,我正在努力转换字符串:
$file = '150220';
转换为 mysql 日期格式。
我试过了
$newDate = date("Y-m-d", strtotime($file));
但是 returns 之后的 2015-02-24(24 是今天的日期)
参见:http://php.net/manual/en/datetime.createfromformat.php
所以你可以使用这个:
$dateTime = DateTime::createFromFormat('ymd', $file);
$newDate = $dateTime->format('Y-m-d');
strtotime
是一个很棒的函数。它在您提供 YYYY-MM-DD 格式但不使用 YY-MM-DD 时有效。
编辑:如评论中所述,您必须 "turn the string into a valid ISO8601 Notations format by prepending '20' - this is understood by strtotime as specified in the docs "
这将适用于未来 85 年的 64 位系统(直到 2038 年适用于 32 位系统)
$file = '150220';
$newDate = date("Y-m-d", strtotime("20$file"));
您必须小心使用 strtotime,因为它 returns 错误时会导致 date
使用今天的日期。
编辑:如果你想 -1 :首先,这段代码有效,它解释了为什么 op 的代码不起作用,然后考虑使用 "Add comment" 按钮。谢谢