在PHP中将一个日期格式转换为另一个日期格式 [英] Convert one date format into another in PHP

查看:203
本文介绍了在PHP中将一个日期格式转换为另一个日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有这样一个简单的方法可以将一个日期格式转换成另一个日期格式:

  $ old_date = date('ymdhi-s'); // works 

$ middle = strtotime($ old_date); // return bool(false)

$ new_date = date('Y-m-d H:i:s',$ middle); //返回1970-01-01 00:00:00

但我当然喜欢返回当前日期,而不是破解黎明。我做错了什么?

解决方案

第二个参数 date()需要是适当的时间戳(1970年1月1日以来的秒)。您正在传递一个字符串,其中date()无法识别。



您可以使用 strtotime() 将日期字符串转换为时间戳。但是,即使strtotime()也不能识别 ymdhis 格式。



PHP 5.3及更高版本



使用 DateTime :: createFromFormat 。它允许您使用 date()语法来指定确切的掩码来解析传入的字符串日期。



PHP 5.2和



您将必须手动解析元素(年,月,日,小时,分钟,秒) code> substr()并将结果传递给 mktime() 将会建立一个时间戳。



但这是很多工作!我建议使用strftime()可以理解的不同格式。 strftime()了解下一次joe将在冰上滑落的任何日期输入。例如,这样做:

  $ old_date = date('l,F d y h:i:s'); // return Saturday,January 30 10 02:06:34 
$ old_date_timestamp = strtotime($ old_date);
$ new_date = date('Y-m-d H:i:s',$ old_date_timestamp);


Is there a simple way to convert one date format into another date format in PHP?

I have this:

$old_date = date('y-m-d-h-i-s');            // works

$middle = strtotime($old_date);             // returns bool(false)

$new_date = date('Y-m-d H:i:s', $middle);   // returns 1970-01-01 00:00:00

But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?

解决方案

The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.

You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.

PHP 5.3 and up

Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.

PHP 5.2 and lower

You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.

But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:

$old_date = date('l, F d y h:i:s');              // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);   

这篇关于在PHP中将一个日期格式转换为另一个日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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