24

Given the following strings:

  • 01/01/11
  • 1/1/11
  • 1/1/2011
  • 01/1/2011
  • 1-1-2011
  • etc

How do I convert these to a Unix timestamp. Note that in most cases, this will be in the format of dd mm yyyy with various delimiters.

hakre
  • 193,403
  • 52
  • 435
  • 836
StackOverflowNewbie
  • 39,403
  • 111
  • 277
  • 441

3 Answers3

44

Look at strtotime, strptime or the DateTime class.

strtotime Example:

$timestamp = strtotime('1/1/2011');

Each function has it's caveat. For instance, the documentation for strtotime states that:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

You could also use preg_match to capture all 3 parts and create your own timestamp using mktime.

preg_match Example:

if ( preg_match('/^(?P<day>\d+)[-\/](?P<month>\d+)[-\/](?P<year>\d+)$/', '1/1/2011', $matches) )
{
  $timestamp = mktime(0, 0, 0, ( $matches['month'] - 1 ), $matches['day'], $matches['year']);
}
rtpHarry
  • 13,019
  • 4
  • 43
  • 64
Francois Deschenes
  • 24,816
  • 4
  • 64
  • 61
  • your regex assumes dd-mm-yyyy format, which I am not sure it is. – StackOverflowNewbie Jun 28 '11 at 04:38
  • @StackOverflowNewbie - Your question said: "Note that in most cases, this will be in the format of dd mm yyyy with various delimiters." so I went with that format but you could add `elseif` statements to the original one that check for different formats and make the `regex` more specific (i.e. instead of \d+ use a pattern that describes 0-12 for the month and 0-31 for the days). Of course, in the case of 1/2/13, it's impossible to tell which is which unless you know the format. – Francois Deschenes Jun 28 '11 at 04:47
5
$to='23.1.2014-18:16:35'
list($part1,$part2) = explode('-', $to);
list($day, $month, $year) = explode('.', $part1);
list($hours, $minutes,$seconds) = explode(':', $part2);
$timeto =  mktime($hours, $minutes, $seconds, $month, $day, $year);
echo $timeto;
Lem
  • 419
  • 5
  • 4
2

You're probably looking for strtotime function.

However just as a caution it will convert each and every possible string format to a unix timestamp (epoch) since it is very difficult to unambiguously parse each and every string to date-time.

Community
  • 1
  • 1
anubhava
  • 761,203
  • 64
  • 569
  • 643