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

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

问题描述

有没有一种简单的方法可以在 PHP 中将一种日期格式转换为另一种日期格式?

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

我有这个:

$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?

推荐答案

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

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.

您可以使用 strtotime() 将日期字符串转换为时间戳.然而,即使是 strtotime() 也无法识别 y-m-d-h-i-s 格式.

PHP 5.3 及更高版本

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

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

PHP 5.2 及更低版本

您必须使用 substr() 手动解析元素(年、月、日、小时、分钟、秒)并将结果交给 mktime() 这将为您构建一个时间戳.

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.

但这是很多工作!我建议使用 strftime() 可以理解的不同格式.strftime() 可以理解 任何 日期输入短于 下次 joe 将在冰上滑倒.例如,这有效:

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天全站免登陆