8

strtotime() in PHP works great if you can provide it with a date format it understands and can convert, but for example you give it a UK date it fails to give the correct unix timestamp.

Is there any PHP function, official or unofficial, that can accept a format variable that tells the function in which format the date and time is being passed?

The closest I have come to doing this is a mixture of date_parse_from_format() and mktime()

// Example usage of the function I'm after
//Like the date() function but in reverse
$timestamp = strtotimeformat("03/05/2011 16:33:00", "d/m/Y H:i:s");
Scott
  • 3,967
  • 9
  • 38
  • 56

3 Answers3

24

If you have PHP 5.3:

$date = DateTime::createFromFormat('d/m/Y H:i:s', '03/05/2011 16:33:00');
echo $date->getTimestamp();
meze
  • 14,975
  • 4
  • 47
  • 52
2

You are looking for strptime, I think. you can use it to parse the date and then use mktime if you need a UNIX timestamp.

function strotimeformat($date, $format) {
  $d = strptime($date, $format);
  return mktime($d['tm_hour'], $d['tm_min'], $d['tm_sec'],
                $d['tm_mon'], $d['tm_mday'], $d['tm_year']);
}

This will work with PHP 5.1 and onwards.

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • no I'm not, I'm looking for something that returns a unix timestamp to an array of values. Plus strptime is not implemented on Windows so not an ideal solution. – Scott May 03 '11 at 15:39
  • Ok. I've updated my answer with a function to give you a timestamp anyway (still not working on Windows though). You can of course do some substring+strpos work (or explode+rearrange+implode) to make it into a US date. – Emil Vikström May 03 '11 at 15:46
  • As mentioned in my question Im already using a combination of `date_parse_from_format()` and `mktime()` in the same way you have shown your code. `date_parse_from_format()` works for all systems but only works on PHP 5.3 >= wereas strptime works on an earlier version but not windows. I'll leave the question open for a few days to see if any other answers come in. – Scott May 03 '11 at 15:52
  • Do you absolutely need to have a format argument? Maybe you can just throw out date_parse_from_format() and use sscanf() instead? That would give you support on most platforms. – Emil Vikström May 03 '11 at 15:56
0

strtotime assumes it's a US date/time when using / as the separator. To get it to think it's a Euro date/time, use - or . as the date separator. You can change the /s to -s or .s with a simple str_replace()

Phoenix
  • 4,488
  • 1
  • 21
  • 13
  • Read the question... I'm quite aware of what strtotime is capable of and how to work around. But that's not what I'm asking... I'm asking for a function that accepts a date in any format along with a string that says what format that date is in and return a unix timestamp. – Scott May 03 '11 at 15:44