Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert date to timestamp in PHP?

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

like image 317
Wizard4U Avatar asked Sep 22 '08 08:09

Wizard4U


People also ask

How do I convert a date to time stamp?

To convert a date string to a timestamp: Pass the date string to the Date() constructor. Call the getTime() method on the Date object. The getTime method returns the number of milliseconds since the Unix Epoch.

How can I timestamp in PHP?

Definition and Usage. The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

What is timestamp format in PHP?

Summary. The date function in PHP is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp. All PHP date() functions use the default time zone set in the php.ini file.

What does date () do in PHP?

Specifies the format of the outputted date string. The following characters can be used: d - The day of the month (from 01 to 31)


1 Answers


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.

like image 194
Owen Avatar answered Sep 30 '22 11:09

Owen