Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: convert date into seconds?

Tags:

php

I've a date like Tue Dec 15 2009. How can I convert it into seconds?

Update: How can I convert a date formatted as above to Unix timestamp?

like image 305
Usman Avatar asked Dec 20 '09 16:12

Usman


Video Answer


2 Answers

I assume by seconds you mean a UNIX timestamp.

strtotime() should help.

like image 109
Pekka Avatar answered Oct 11 '22 23:10

Pekka


You can use the strtotime function to convert that date to a timestamp :

$str = 'Tue Dec 15 2009';
$timestamp = strtotime($str);

And, just to be sure, let's convert it back to a date as a string :

var_dump(date('Y-m-d', $timestamp));

Which gives us :

string '2009-12-15' (length=10)

(Which proves strtotime did understand our date ^^ )



[edit 2012-05-19] as some other questions might point some readers here: Note that strtotime() is not the only solution, and that you should be able to work with the DateTime class, which provides some interesting features -- especially if you are using PHP >= 5.3


In this case, you could use something like the following portion of code :

$str = 'Tue Dec 15 2009';
$format = 'D F d Y';
$dt = DateTime::createFromFormat($format, $str);
$timestamp = $dt->format('U');


DateTime::createFromFormat() allows one to create a DateTime object from almost any date, no matter how it's formated, as you can specify the format you date's in (This method is available with PHP >= 5.3).

And DateTime::format() will allow you to format that object to almost any kind of date format -- including an UNIX Timestamp, as requested here.

like image 40
Pascal MARTIN Avatar answered Oct 11 '22 21:10

Pascal MARTIN