PHP has a really useful date() function for formatting dates from timestamps. When used in conjunction with strtotime() you can do some really quick and easy manipulation and formatting of dates.
The PHP date() function works like this:
You pass it a format string to specify what format you want the date in, and an optional timestamp as the date to format. If you don't specify the timestamp then the current timestamp is used. The timestamp is a UNIX timestamp, which is an integer value; eg December 20th at 2pm would be represented as 1198112400 as a UNIX timestamp.
Passing the above example timestamp (which is the publish date and time of this post) would yield the following examples:
PHP code to show the date in YYYY-MM-DD format (MySQL date format):
Result:
PHP code to show the date in YYYY-MM-DD HH:MM:SS format (MySQL datetime format):
Result:
PHP code to show the date of the week, month name, day of the month with ordinal suffix (ie st, nd, rd)) and year:
Result:
PHP code to show the RFC 2822 formatted date:
Result:
A full list of formatting placeholders can be found in the PHP Manual.
Using strtotime to convert dates to timestamps
A date and time stamp retrieved from a database query is often in the format YYYY-MM-DD HH:MM:SS which is not the sort of timestamp that can be accepted by the date() function. If you pass a string value to date() as the timestamp then it will first convert it to an integer which will yield 0, and is the equivilent of January 1st 1970.
First you must convert the date time string value to an integer, which can easily be done using the strtotime() PHP function like so:
Tomorrow I'll look at strtotime() further, and the useful things that can be done with it.
0 comments:
Post a Comment