PHP date format converting
Here is what I have:
$dateFormat = 'M d, Y';
$dateString = 'January 23, 2010';
What I need is a timestamp of $dateString
so I can do this:
$newFormattedDate = date('Y-m-d', $timestamp);
I tried to use strtotime
function but it tries to find out the format itself and doesn't work always. In my situation I know both the date string and date format.
How can I set $timestamp
to an appropriate value for use with the date
function?
EDIT: I need this to work in both Linux and Windows environments.
EDIT: The solution must support PHP version 4 or higher
EDIT: MySQL has a function called STR_TO_DATE
which takes a date string and a date format and returns Y-m-d
formatted date string. Any equivalent function for php works for me also.
As of PHP5.3 you can use the DateTime API
$dt = date_create_from_format('M d, Y', 'January 23, 2010');
echo date_timestamp_get($dt);
or with OOP notation
$dt = DateTime::createFromFormat('M d, Y', 'January 23, 2010');
echo $dt->getTimestamp();
Note that while DateTime
is available in PHP < 5.3, the methods used above are not and while you could simulate ->getTimestamp()
with ->format('U')
, there is no easy workaround for createFromFormat()
An alternative would be to use Zend_Date
from Zend Framework:
$date = new Zend_Date('Feb 31, 2007', 'MM.dd.yyyy');
echo $date->get(Zend_Date::TIMESTAMP);
Use strptime
, mktime
and strftime
:
$ftime = strptime($dateString, $dateFormat);
$timestamp = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1,
$ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900);
echo strftime('Y-m-d', $timestamp);
Please note that strptime
is not implemented on Windows platforms.
Note that the arguments to mktime
are somewhat unusual - strptime
returns a day of the year (between 0-365, inclusive) rather than a day of the month and a month, so we set the month parameter to mktime
to 1, and add 1 to the day of the year. Also, strptime
returns years since 1900 for the year value it returns, so we need to add 1900 to the year before passing it through to mktime
.
Also, you might want to check whether $ftime
is FALSE
before passing it into mktime
. strptime
returning FALSE
denotes that the inputs $dateString
is not a valid date format according to $dateFormat
.
Given my understanding of the question and what is available in PHP, you need to relax your expectations somewhere or other.
A 'simple' solution (which has already been discounted) would be to force using PHP 5.3 and the tools available in it.
A less simple solution would be to take those additions and port them over to PHP-land (with PHP 4 compatibility, good luck).
Another route of exploration would be to consider the occasions where strtotime
does not work for you and working around those limitations.
How widely variant are your format strings? It may be possible to come up with a solution mapping format strings to functions/methods (to do that date parsing) providing they're pretty restricted.