I need to get UNIX timestamp parsing not-only-numeric dates written in specific locale.
An example date (Italian locale) is:
2014 Settembre 25, 19:12:55
This is the code I currently wrote, but it works only for English locale...:
<?php
$format = "Y M d, H:i:s";
$timezone = "Europe/Rome"; # (timezone is not meaningful for this example...)
$date = "2014 September 25, 19:12:55";
$locale = "en";
print date2Timestamp($format, $locale, $timezone, $date);
# outputs "1411621975", o.k.
$date = "2014 Settembre 25, 19:12:55";
$locale = "it";
print date2Timestamp($format, $locale, $timezone, $date);
# outputs "PHP Fatal error: Call to a member function getTimestamp() on a non-object", error!
/**
* Converts a date from a custom format to UNIX timestamp.
*
* @param string $format source date format
* @param string $locale source locale
* @param string $timezone source timezone
* @param string $date source date to be converted
* @return string UNIX timestamp conevrsion of the given date
*/
function date2Timestamp($format, $locale, $timezone, $date) {
$oldLocale = setlocale(LC_TIME, 0);
setlocale(LC_TIME, $locale);
$dt = DateTime::createFromFormat($format, $date, new DateTimeZone($timezone));
setlocale(LC_TIME, $oldLocale);
return $dt->getTimestamp();
}
?>
So, effectively, as documented, PHP DateTime does not take into account locales... :-(
Any suggestion how to get timestamp from localized date in PHP?
UPDATE:
As indirectly suggested in comments, I tested strptime().
It doesn't seem to work as expected, nor even for English formatted dates... :-(
$ php --version
PHP 5.3.3 (cli) (built: Oct 30 2014 20:12:53)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
<?php
$locale = "en";
setlocale(LC_TIME, $locale);
$format = "%Y %m %d, %H:%M:%S";
$date = "2014 9 25, 19:12:55";
print "strptime with decimal month:"; var_dump(strptime($date, $format));
$format = "%Y %F %d, %H:%M:%S";
$date = "2014 September 25, 19:12:55";
print "strptime with textual month:": var_dump(strptime($date, $format));
?>
Output:
strptime with decimal month: array(9) {
["tm_sec"]=>
int(55)
["tm_min"]=>
int(12)
["tm_hour"]=>
int(19)
["tm_mday"]=>
int(25)
["tm_mon"]=>
int(8)
["tm_year"]=>
int(114)
["tm_wday"]=>
int(4)
["tm_yday"]=>
int(267)
["unparsed"]=>
string(0) ""
}
strptime with textual month: bool(false)