简体   繁体   中英

Change the format of a Date in PHP


I have this code :


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

I want to change a date ($statuses[$i]['created_at']) which is for example "Sat Dec 04 17:43:38 +0000 2010" into for example 2010-12-05 10:00:26 , but if I run the code I pasted you, in returns Array ( )
How can I change the format of that date?

具有日期功能:

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

This is because strptime returns an Array .

See http://php.net/manual/en/function.strptime.php

You can construct a result from that array:

$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']
);

This should work in PHP >= 5.3, but it fails on my installation (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');

See this bug report:

http://bugs.php.net/51393

However, this works, and should work in PHP < 5.3 too:

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

Prints:

2010-12-04 17:43:38

It appears as though other date/time parsing functions which can be passed an explicit conversion format also fail when supplied with the timezone offset:

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

// $dt_array == false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM