开发者

PHP date format question

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']) . "</eve开发者_高级运维ntdate>\n";

I want it to display as: Saturday 3rd April

Any help would be appreciated!

Simon


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()


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


Alternatively, you could let MySQL format the date for you on retrieval (makes for cleaner code in building your XML):

SELECT
  event_date,
  DATE_FORMAT( event_date, '%W %D %M' ) AS event_date_formatted
FROM
  ...

Then in PHP:

$xml_output .= "\t\t<eventdate>" . $row['event_date_formatted'] . "</eventdate>\n";

Also:
MySQL date formatting functions are a bit more flexible, as they don't depend on unix timestamps that much (if you use DATETIME fields, that is). Admittedly a bit unlikely perhaps; but if your event_date exceeds the unsigned 32 bit integer timestamp boundaries, your pretty much screwed with php's date function. Try formatting a date before January 1st 1970, or after January 19th 2038, and you will see what I mean.


Use the strftime() function to convert the datetime you get from a database in a unix timestamp suitable for date():

date("l jS F", strtotime($row['event_date']))


PHP date function expects to receive a unix timestamp.

Change the format of the date you pull from the db to unix timestamp.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜