How to convert date to timestamp in PHP?
Asked Answered
J

23

384

How do I get timestamp from e.g. 22-09-2008?

Jiminez answered 22/9, 2008 at 8:41 Comment(0)
R
653


This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.

If you don't care about timezone, or want to use the time zone your server uses:

$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093324 (This will differ depending on your server time zone...)


If you want to specify in which time zone, here EST. (Same as New York.)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('EST')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093305


Or if you want to use UTC. (Same as "GMT".)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('UTC')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093289


Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.

Resee answered 22/9, 2008 at 8:45 Comment(5)
A completely valid answer, but I'm surprised that Armin Ronacher's answer hasn't matched it in upvotes -- ambiguity is ALWAYS bad.Amygdala
@Devner Well, it seems, on my server, that format isn't supported. Maybe it's different with yours.Tuneberg
Beware strtotime('2012') might result in a timestamp of today and time 20:12Airlee
This solution can lead to an unexpected behavior. Those who use PHP 5.3+ should adopt Prof. Falken answer, in which one has full control over the date format.Superpatriot
@LucaFagioli It seems Prof.Falken, desperate to see that answer with so many upvotes, updated it and included his own science.Hystero
N
189

There is also strptime() which expects exactly one format:

$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);

Warnings:

  • This function is not implemented on Windows
  • This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.
Neoteric answered 22/9, 2008 at 8:52 Comment(6)
it should be tm_mon instead of tm_month and tm_mday instead of tm_dayBoulware
Beware, strptime function is not available on Windows.Threephase
Those on Windows and PHP 5.3.0+, consider using date_parse_from_format instead of strptime.Alasteir
... because strptime is not implemented in Windows platforms.Walley
Since this is a highly voted answer, will you consider editing it to an answer which works on PHP for Windows as well as unixen? And IMHO ideally it should mention timezones.Unsupportable
Also, since PHP 5.3 php.net/manual/en/function.date-parse-from-format.php is recommended instead.Unsupportable
R
136

With DateTime API:

$dateTime = new DateTime('2008-09-22'); 
echo $dateTime->format('U'); 

// or 

$date = new DateTime('2008-09-22');
echo $date->getTimestamp();

The same with the procedural API:

$date = date_create('2008-09-22');
echo date_format($date, 'U');

// or

$date = date_create('2008-09-22');
echo date_timestamp_get($date);

If the above fails because you are using a unsupported format, you can use

$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U'); 

// or

$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');

Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.

Yet another alternative is to use the IntlDateFormatter API:

$formatter = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'GMT',
    IntlDateFormatter::GREGORIAN,
    'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');

Unless you are working with localized date strings, the easier choice is likely DateTime.

Renaerenaissance answered 17/5, 2011 at 9:1 Comment(3)
I'd recommend this over my answer nowadays.Norite
Arggg. ! Don't forget the ! My date based timestamp was changing on each refresh and driving me mad - because DateTime was helpfully adding the current time without asking or being told. Grrr.Schizoid
I want to add that I recommend against ambiguous date parsing, and that the date format should be given explicitly when parsing date strings.Unsupportable
K
116

Be careful with functions like strtotime() that try to "guess" what you mean (it doesn't guess of course, the rules are here).

Indeed 22-09-2008 will be parsed as 22 September 2008, as it is the only reasonable thing.

How will 08-09-2008 be parsed? Probably 09 August 2008.

What about 2008-09-50? Some versions of PHP parse this as 20 October 2008.

So, if you are sure your input is in DD-MM-YYYY format, it's better to use the solution offered by @Armin Ronacher.

Kirsch answered 22/9, 2008 at 16:22 Comment(4)
Valid concern. I guess strtotime() relies in your locale.Norite
Note: on most non-english speaking countries, the format is dd-mm-yyyy, not mm-dd-yyyy.Advised
@CamiloMartin Most non-english spoken countries use the first format you stated but the DB usually store the date in YYYY-mm-dd The conversion happens only to display to the usersWoodwaxen
@DannyG just looked at the docs and it seems you're right if by DB you mean MySQL. But it does seem ridiculous to do this...Advised
U
65


This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.

If you don't care about timezone, or want to use the time zone your server uses:

$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093324 (This will differ depending on your server time zone...)


If you want to specify in which time zone, here EST. (Same as New York.)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('EST')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093305


Or if you want to use UTC. (Same as "GMT".)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('UTC')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093289


Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.

Unsupportable answered 11/10, 2013 at 14:21 Comment(1)
Hey Falken, you are welcome. However it is probably better specifying that this solution applies to PHP 5.3+Superpatriot
N
45

Using mktime:

list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);
Norite answered 22/9, 2008 at 8:44 Comment(3)
That's what I've always done. Explode it on - or / or . or whatever it's separated on, then mktime.Salvatoresalvay
There is a note in the PHP manual for the last parameter of the mktime function: "As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead." I've yet to discover what the new features are that they speak about though, as they haven't linked to it!Gunnar
This is far better than strtotime() For some reason strtotime() doesn't work on certain dates, and is therefore very unreliable.Lysenkoism
E
20

Using strtotime() function you can easily convert date to timestamp

<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');

//define date and time
$date = date("d M Y H:i:s");

// output
echo strtotime($date);
?> 

More info: http://php.net/manual/en/function.strtotime.php

Online conversion tool: http://freeonlinetools24.com/

Endoderm answered 6/4, 2015 at 22:24 Comment(1)
To future readers - strtotime() was an accident and it's use should not be encouraged. It's ambiguous, because it tries to guess at the date format. Even if you use it correctly, it makes your code harder to understand and reason about and you run the risk of a change being made to your code base which will introduce errors, because no matter what you give to strtotime(), it will make it's best to guess. That guess may be incorrect, but you will get no indication it guessed incorrectly. It's a footgun. Use it if you like, but novice users can use a caveat I think. Caution: footgun aheadUnsupportable
S
14

Here is a very simple and effective solution using the split and mtime functions:

$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date); 

//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);

It worked like a charm for me.

Stratovision answered 8/9, 2010 at 16:7 Comment(1)
Note that split() is now deprecated, but if you're using an ol' php version, it's working great!Extemporary
W
7

Use PHP function strtotime()

echo strtotime('2019/06/06');

date — Format a local time/date

Wyckoff answered 9/2, 2018 at 10:3 Comment(2)
he said, date to timestamp, not time to datePolished
Check this now.Wyckoff
P
6

If you know the format use strptime because strtotime does a guess for the format, which might not always be correct. Since strptime is not implemented in Windows there is a custom function

Remember that the returnvalue tm_year is from 1900! and tm_month is 0-11

Example:

$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)
Propose answered 7/1, 2010 at 13:26 Comment(0)
S
6

Given that the function strptime() does not work for Windows and strtotime() can return unexpected results, I recommend using date_parse_from_format():

$date = date_parse_from_format('d-m-Y', '22-09-2008');
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);
Snarl answered 11/6, 2012 at 10:36 Comment(1)
Note: with strtotime(): 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. So I think don't need to use strptime()Blackfoot
C
6

If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat():

$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
    die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22

It's obvious in this case, but e.g. 03-04-2008 could be 3rd of April or 4th of March depending on where you come from :)

Carpet answered 13/12, 2012 at 3:32 Comment(1)
DateTime::createFromFormat returns false on error, not null.Procurable
L
4
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>

http://php.net/manual/en/function.date.php

Lost answered 15/11, 2013 at 0:26 Comment(0)
R
4
$time = '22-09-2008';
echo strtotime($time);
Rajewski answered 31/7, 2014 at 7:31 Comment(0)
T
3

Here is how I'd do it:

function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')
{
    //returns an array containing day start and day end timestamps
    $old_timezone=date_timezone_get();
    date_default_timezone_set($timezone);
    $date=strptime($date,$format);
    $day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));
    $day_end=$day_start+(60*60*24);
    date_default_timezone_set($old_timezone);
    return array('day_start'=>$day_start, 'day_end'=>$day_end);
}

$timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');
$day_start=$timestamps['day_start'];

This way, you let the function know what date format you are using and even specify the timezone.

Thinking answered 13/6, 2010 at 13:0 Comment(0)
S
3
function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = "#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$#is" ) {
    $return = false;
    $_timezone = date_default_timezone_get();
    date_default_timezone_set( $timezone );
    if( preg_match( $expression, $date, $matches ) )
        $return = date( "Y-m-d " . ( $slash_time ? '00:00:00' : "h:i:s" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date("h:i:s") ) );
    date_default_timezone_set( $_timezone );
    return $return;
}

// expression may need changing in relation to timezone
echo date_to_stamp('19/03/1986', false) . '<br />';
echo date_to_stamp('19**03**1986', false) . '<br />';
echo date_to_stamp('19.03.1986') . '<br />';
echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';
echo date('Y-m-d h:i:s') . '<br />';

//1986-03-19 02:37:30
//1986-03-19 02:37:30
//1986-03-19 00:00:00
//1986-03-19 05:37:30
//2012-02-12 02:37:30
Stafani answered 11/2, 2012 at 11:26 Comment(0)
S
3
<?php echo date('U') ?>

If you want, put it in a MySQL input type timestamp. The above works very well (only in PHP 5 or later):

<?php $timestamp_for_mysql = date('c') ?>
Slender answered 13/12, 2012 at 3:20 Comment(0)
H
1

For PHP >=5.3, 7 & 8 the this may work-

$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format. 
                                                           //just need to keep in mind that date and format matches.

$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp

$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.

Docs:

Heretofore answered 24/3, 2022 at 17:3 Comment(0)
T
1

If you already have the date in that format, you only need to call the "strtotime" function in PHP.

$date = '22-09-2008';
$timestamp = strtotime($date);
echo $timestamp; // 1222041600

Or in a single line:

echo strtotime('22-09-2008');

Short and simple.

Thereupon answered 12/8, 2022 at 16:24 Comment(0)
B
0

Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to timestamp using strtotime. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.

Please see this example: https://3v4l.org/BRlmV

function getthistime($type, $modify = null) {
    $now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));
    if($modify) {
        $now->modify($modify);
    }
    if(!isset($type) || $type == 'datetime') {
        return $now->format('Y-m-d H:i:s');
    }
    if($type == 'time') {
        return $now->format('H:i:s');
    }
    if($type == 'timestamp') {
        return $now->getTimestamp();
    }
}
function timestampfromdate($date) {
    return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();
}

echo getthistime('timestamp')."--".
    timestampfromdate(getthistime('datetime'))."--".
    strtotime(getthistime('datetime'));

//getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)
//getthistime('timestamp') == strtotime(getthistime('datetime')) (false)
Bistort answered 19/5, 2016 at 11:50 Comment(0)
S
0

I use this to get my timestamp.

$timestamp = strtotime("2020-05-03 04:30:55");
print_r($timestamp); or echo $timestamp;
Seedling answered 12/7, 2023 at 22:31 Comment(0)
M
-1

I have used this format: $presentDateTime = strtotime(date('Y-m-d H:i:s'));

Merritt answered 30/11, 2022 at 10:13 Comment(0)
S
-4

If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z) to timestamp, here's how you'd do it:

function UTCToTimestamp($utc_datetime_str)
{
    preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
    $datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];

    return strtotime($datetime_str);
}

$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);
Syncopated answered 27/2, 2016 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.