Thingamajig
Thingamajig

Reputation: 4465

Formatting date in PHP

Formatting the date below is not working. The date_published after the echo date_published is in this format: Sat, 15 Sep 2012 10:10:37 -0400

The second echo, echoes nothing.

$date_published = $abc[$z]['pubDate'];
echo $date_published;
$date_published = date('Y-m-d H:i:s',$date_published);
echo $date_published;

Upvotes: 0

Views: 4946

Answers (4)

Ross Smith II
Ross Smith II

Reputation: 12189

This script:

$date_published = 'Sat, 15 Sep 2012 10:10:37 -0400';
printf("date_published=%s\n", $date_published);
$time = strtotime($date_published);
printf("time=%s\n", $time);

$date = date('Y-m-d H:i:s',$time);
printf("date=%s\n", $date);

# if you are using PHP 5.2 or greater:
$dt = new DateTime($date_published);
$date = $dt->format('Y-m-d H:i:s');
printf("date=%s\n", $date);

produces this output:

date_published=Sat, 15 Sep 2012 10:10:37 -0400
time=1347718237
date=2012-09-15 07:10:37
date=2012-09-15 10:10:37

Note that date() is displaying the time to my local timezone (PDT or -07:00), but DateTime() is displaying the time in the original timezone (-04:00).

Upvotes: 1

Rubin Porwal
Rubin Porwal

Reputation: 3845

For formatting a date using php, you need to use date function which accepts date format and timestamp as arguments.

In the above example you need to generate timestamp for $date_published using strtotime() and pass it as a second argument in date function.

eg $date_published = date('Y-m-d H:i:s', strtotime($date_published));

Upvotes: 0

Mihai Iorga
Mihai Iorga

Reputation: 39724

Use strtotime():

$date_published = $abc[$z]['pubDate'];
echo $date_published;
$date_published = date('Y-m-d H:i:s', strtotime($date_published));
echo $date_published;

Upvotes: 1

Brendan
Brendan

Reputation: 4565

Use strtotime()

$date_published = date('Y-m-d H:i:s',strtotime($date_published));

date() expects a unix timestamp as the second parameter.

Upvotes: 1

Related Questions