0


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?

Francesc
  • 1,339
  • 4
  • 16
  • 34

3 Answers3

3

With the date function:

$myDate = date('Y-m-d h:i:s', $timestamp);
yan.kun
  • 6,820
  • 2
  • 29
  • 38
  • The date function requires a timestamp as its second argument and the strptime function returns an array. I think that `$timestamp` should therefore be `$timestamp_bad`, so the strptime step is skipped completely. – Mike Dec 05 '10 at 10:30
2

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']
);
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
0

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
Mike
  • 21,301
  • 2
  • 42
  • 65