将字符串转换为日期和日期时间 [英] Converting string to Date and DateTime

查看:39
本文介绍了将字符串转换为日期和日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a PHP string in the format of mm-dd-YYYY (for example, 10-16-2003), how do I properly convert that to a Date and then a DateTime in the format of YYYY-mm-dd? The only reason I ask for both Date and DateTime is because I need one in one spot, and the other in a different spot.

推荐答案

在第一次约会时使用 strtotime() 然后使用 date('Ym-d') 进行转换它回来了:

Use strtotime() on your first date then date('Y-m-d') to convert it back:

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

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

echo $newformat;
// 2003-10-16

请注意,在 / 和连字符 - 之间存在区别="noreferrer">strtotime() 函数.引用自 php.net:

Make note that there is a difference between using forward slash / and hyphen - in the strtotime() function. To quote from php.net:

采用 m/d/y 或 d-m-y 格式的日期通过查看消除歧义各种之间的分隔符组件:如果分隔符是一个斜线 (/),那么美国的 m/d/y 是假定;而如果分隔符是破折号 (-) 或点 (.),然后假定为欧洲 d-m-y 格式.

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.

为避免潜在的歧义,最好尽可能使用 ISO 8601 (YYYY-MM-DD) 日期或 DateTime::createFromFormat().

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

这篇关于将字符串转换为日期和日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆