Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: convert date string to Unix timestamp

Tags:

php

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.

like image 694
StackOverflowNewbie Avatar asked Jun 28 '11 02:06

StackOverflowNewbie


People also ask

Which PHP function converts an English text DateTime into a Unix timestamp?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

What is Unix timestamp in PHP?

Simply put, the Unix timestamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the Unix timestamp is merely the number of seconds between a particular date and the Unix Epoch.

What is the use of Strtotime function in PHP?

The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description.


3 Answers

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']);
}
like image 143
Francois Deschenes Avatar answered Oct 26 '22 04:10

Francois Deschenes


$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;
like image 5
Lem Avatar answered Oct 26 '22 03:10

Lem


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.

like image 2
anubhava Avatar answered Oct 26 '22 05:10

anubhava