Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date format question

Tags:

php

datetime

I'm trying to format some dates in PHP (i'm a Coldfusion programmer, so the syntax is similar, but i'm stuck!).

The dates are formatting perfectly into the display I want. However, they all return 1st Jan 1970.

Can anyone shed any light on this?

For background, I am pulling a date from a datetime column in mySQL. The raw date i'm trying to format is....

2010-04-03 00:00:00

Here is the line of code i'm using....

$xml_output .= "\t\t<eventdate>" . date("l jS F", $row['event_date']) . "</eventdate>\n";

I want it to display as: Saturday 3rd April

Any help would be appreciated!

Simon

like image 735
Simon Hume Avatar asked Jul 03 '26 11:07

Simon Hume


2 Answers

The second parameter to date() needs to be a UNIX timestamp.

Convert your date string it into a timestamp first using strtotime():

$timestamp = strtotime($row["event_date"]);
echo date("l jS F", $timestamp); // Saturday 3rd April 

Manual pages:

  • date()

  • strtotime()

like image 50
Pekka Avatar answered Jul 05 '26 14:07

Pekka


The date function works with an UNIX timestamp (i.e. a number of seconds since January 1, 1970), and not a date passed as a string.

This means you have to first convert your date to a timestamp, using strtotime, for instance :

$timestamp = strtotime('2010-04-03 00:00:00');

And, then, you can use the date function on this timestamp :

echo date('l jS F', $timestamp);

Which gets you the output you wanted :

Saturday 3rd April
like image 38
Pascal MARTIN Avatar answered Jul 05 '26 14:07

Pascal MARTIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!