gpt4 book ai didi

php - 将字符串转换为日期和日期时间

转载 作者:IT老高 更新时间:2023-10-28 11:38:23 25 4
gpt4 key购买 nike

如果我有 mm-dd-YYYY 格式的 PHP 字符串(例如,10-16-2003),我如何正确地将其转换为 Date,然后是 YYYY-mm-dd 格式的 DateTime?我要求 DateDateTime 的唯一原因是因为我需要一个在一个位置,另一个在另一个位置。

最佳答案

在您的第一个日期使用 strtotime() 然后 date('Y-m-d') 将其转换回来:

$time = strtotime('10/16/2003');

$newformat = date('Y-m-d',$time);

echo $newformat;
// 2003-10-16

请注意,在 strtotime() 中使用正斜杠 / 和连字符 - 是有区别的。功能。引用php.net:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

关于php - 将字符串转换为日期和日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6238992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com