Reputation: 3773
I am retrieving a date from the database in the format YYYYMMDD. It is a wordpress value and has to be stored like this in order for me to perform specific queries with it that work with wordpress.
I want to convert it to no leading zeros day, and short month, e.g. 3 DEC, for 20121203. However php's date function says it takes a unix timestamp, so I need to convert it to such before I can manipulate it. How can I do this?
Upvotes: 0
Views: 434
Reputation: 1493
strtotime
should be able to convert that format to a UNIX timestamp
$date = '20120101';
echo date('j M', strtotime($date));
// output: 1 Jan
This also depends on your locale settings, by the way.
EDIT: Important Note: if a date is ambiguous strtotime returns false!
You can also use the mktime()
function, which accepts integer values for hour, minute, second, month, day, year to produce a unix timestamp:
$year = 2012;
$month = 1;
$day = 1;
$timestamp = mktime(0,0,0,$month,$day,$year);
echo date('j M', $timestamp);
// output: 1 Jan
EDIT: Another way is to retrieve the value from the database already formatted (assuming MySQL):
SELECT UNIX_TIMESTAMP(20120101)
// outputs 1325372400 (== mktime(0,0,0,1,1,2012))
Upvotes: 1