Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

php - 将字符串转换为Date和DateTime(Converting string to Date and 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 ?

(如果我有一个mm-dd-YYYY格式的PHP字符串(例如,2003年10月16日),如何正确地将其转换为Date然后是DateTime ,格式为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.

(我同时要求DateDateTime的唯一原因是我需要一个地点,另一个地点需要另一个地点。)

  ask by Chris Pinski translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

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

echo $newformat;
// 2003-10-16

Make note that there is a difference between using forward slash / and hyphen - in the strtotime() function.

(请注意,在strtotime()函数中使用正斜杠/和连字符-是有区别的。)

To quote from php.net:

(引用php.net:)

Dates in the m/d/y or dmy 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;

(通过查看各个组成部分之间的分隔符,可以消除m / d / y或dmy格式的日期的歧义:如果分隔符为斜杠(/),则假定为美国m / d / y;)

whereas if the separator is a dash (-) or a dot (.), then the European dmy format is assumed.

(相反,如果分隔符是破折号(-)或点(。),则采用欧洲dmy格式。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...