在PHP中更改日期的格式

时间:2010-12-05 09:22:02

标签: php date


我有这段代码:


$timestamp_bad = strtotime($statuses[$i]['created_at']);
$timestamp = strptime(strftime("%Y-%m-%d %T", $timestamp_bad), "%Y-%m-%d %T");
echo $timestamp;

我想将日期($ status [$ i] ['created_at'])(例如"Sat Dec 04 17:43:38 +0000 2010")更改为例如2010-12-05 10:00:26,但如果我运行了我粘贴的代码,在回报Array ( )中 如何更改该日期的格式?

3 个答案:

答案 0 :(得分:3)

使用日期功能:

$myDate = date('Y-m-d h:i:s', $timestamp);

答案 1 :(得分:2)

这是因为strptime会返回Array

请参阅http://php.net/manual/en/function.strptime.php

您可以从该数组构造结果:

$tm = strptime(...);
printf('%04d-%02d-%02d %02d:%02d:%02d',
   $tm['tm_year'] + 1900,
   $tm['tm_mon'] + 1,
   $tm['tm_mday'],
   $tm['tm_hour'],
   $tm['tm_min'],
   $tm['tm_sec']
);

答案 2 :(得分:0)

这应该在PHP> = 5.3中有效,但在我的安装上失败(PHP 5.3.2-1ubuntu4.5):

$timestamp_bad = "Sat Dec 04 17:43:38 +0000 2010";
$dt = DateTime::createFromFormat('D M d H:i:s O Y', $timestamp_bad);
echo $dt->format('Y-m-d H:i:s');

请参阅此错误报告:

http://bugs.php.net/51393

然而,这有效,并且应该在PHP< 5.3也是:

$timestamp_bad = "Sat Dec 04 17:43:38 +0000 2010";
$timestamp = strtotime($timestamp_bad);
echo date('Y-m-d H:i:s', $timestamp);

打印:

2010-12-04 17:43:38

似乎其他日期/时间解析函数可以传递显式转换格式,但在提供时区偏移时也会失败:

$timestamp_bad = "Sat Dec 04 17:43:38 +0000 2010";
$dt_array = strptime($timestamp_bad, '%a %m %d %T %z %Y');

// $dt_array == false