This article demonstrates how to convert a date to a Unix timestamp in PHP. The Unix timestamp starts at the Unix epoch on January 1st, 1970, 00:00:00 UTC, and contains the total number of seconds elapsed until the specified time.

1. Using strtotime() function

A straightforward method is to use the strtotime() function to convert the given date to a Unix timestamp. The function expects the given string to be a valid date and time format. For example, the following script shows the usage of strtotime() for parsing the English date format YYYY-MM-DD into the number of seconds since the Unix epoch.

Download  Run Code

 
It is worth noting that a Unix timestamp does not contain the timezone information. If you need the current time measured in the number of seconds since the Unix Epoch, consider using the time() function.

Download  Run Code

2. Using DateTime::format() function

The DateTime class stores date and time information, and supplies methods for manipulating date and time. One such method is DateTime::format(), which returns a date formatted according to the given format. The U format parameter is useful to get the number of seconds since the Unix epoch.

Download  Run Code

 
The DateTime::format() is an object-oriented style function. Equivalently, you may use the procedural function date_format() to get the formatted date according to the given format.

Download  Run Code

3. Using DateTime::getTimestamp() function

The DateTime class also has an in-built method, DateTime::getTimestamp() to get the Unix timestamp representing the date that corresponds to the DateTime object. The following script provides an illustration:

Download  Run Code

 
You may also use the date_timestamp_get() function, which is an alias of DateTime::getTimestamp().

Download  Run Code

4. Using mktime() function

The mktime() returns the Unix timestamp corresponding to the given arguments. The function takes the arguments in order: hour, minute, second, month, day, and year, and returns the number of seconds between the Unix epoch and the specified time.

Download  Run Code

That’s all there is to converting a date to a timestamp in PHP.