开发者

Convert PHP datetime to MySQL RFC-822 valid Date-Time for RSS Feed

I want to add a date/time, created in PHP, to MySQL that is valid in a RSS Feed.

I'm using in PHP

$d = date( 'Y-m-d H:i:s T', time() );
$mysqldate = gmdate(DATE_RSS, strtotime($d));

insertin开发者_C百科g that into a DATETIME field in my database

But it saves it in this format Wed, 02 Oct 2002 08:00:00

and it need to be in this format to be RFC-822 valid Wed, 02 Oct 2002 08:00:00 EST


Use DATE_RFC822 instead of DATE_RSS


Why are you converting a php date time to a string, then converting that string back into a datetime object again? that's a serious waste of cpu cycles. why not simply do

$mysqldate = gmdate(DATE_RSS, time())?

as well, gmdate generates a UTC timestamp, for which there is no timezone - it's always GMT+0


Answer is very simple just use this format:

<pubDate>'.date('r', strtotime($rss_row['your_date_field'])).'</pubDate>

The original echo is:

echo date('r', strtotime($my_date));

This turns the datetime from inside our MySQL table which is formatted like: YYYY-MM-DD HH:MM:SS and turns it into a UNIX string that represents the same date.

Once we do that to our date, we have the date() function’s many wonders at our disposal. Going into those many wonders is more than I’ll get into here, but I’ve posted about it here.

In this particular case, adding the ‘r’ parameter to the date() function does all the work of reformatting our UNIX string into our RSS feed date format.

It’s that easy.


When saving something into a MySQL DATETIME field, you can not specify the format. DATETIMEs are stored in an internal format that is only concerned with the time value, not with the formatting. You will always have to format the date the way you need it after (or while) retrieving it from the database:

date(DATE_RSS, strtotime($dateFromDatabase));

To insert a date into the database you just need to provide it in a format MySQL understands, it will then be converted to said internal format and the formatting will be lost:

sprintf("INSERT INTO `foo` (`date`) VALUES('%s')", date('Y-m-d H:i:s'))


date('r', strtotime($object->pubDate))

-works nice


Actually DATETIME fields don't save any information about the timezone (http://dev.mysql.com/doc/refman/5.1/en/datetime.html).

So you need to append the timezone AFTER fetching the date from the database.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜