How to convert a date YYYY-MM-DD to epoch in PHP

Gianluca Ghettini picture Gianluca Ghettini · Mar 13, 2013 · Viewed 48.4k times · Source

As per title: how to convert a string date (YYYY-MM-DD) to epoch (seconds since 01-01-1970) in PHP

Answer

Nick Audenaerde picture Nick Audenaerde · Mar 13, 2013

Perhaps this answers your question

http://www.epochconverter.com/programming/functions-php.php

Here is the content of the link:

There are many options:

  1. Using 'strtotime':

strtotime parses most English language date texts to epoch/Unix Time.

echo strtotime("15 November 2012");
// ... or ...
echo strtotime("2012/11/15");
// ... or ...
echo strtotime("+10 days"); // 10 days from now

It's important to check if the conversion was successful:

// PHP 5.1.0 or higher, earlier versions check: strtotime($string)) === -1
if ((strtotime("this is no date")) === false) {
   echo 'failed';
 }

2. Using the DateTime class:

The PHP 5 DateTime class is nicer to use:

// object oriented
$date = new DateTime('01/15/2010'); // format: MM/DD/YYYY
echo $date->format('U'); 

// or procedural
$date = date_create('01/15/2010'); 
echo date_format($date, 'U');

The date format 'U' converts the date to a UNIX timestamp.

  1. Using 'mktime':

This version is more of a hassle but works on any PHP version.

// PHP 5.1+ 
date_default_timezone_set('UTC');  // optional 
mktime ( $hour, $minute, $second, $month, $day, $year );

// before PHP 5.1
mktime ( $hour, $minute, $second, $month, $day, $year, $is_dst );
// $is_dst : 1 = daylight savings time (DST), 0 = no DST ,  -1 (default) = auto

// example: generate epoch for Jan 1, 2000 (all PHP versions)
echo mktime(0, 0, 0, 1, 1, 2000);