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

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

问题描述

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

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或dmy格式的
日期
各个
组件之间的分隔符:如果分隔符是
斜杠(/),则美式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.

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

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