This is a short PHP guide on how to convert a regular date string into a Unix timestamp. As you probably already know, “Unix Time” is the number of seconds that have passed since the 1st of January, 1970.
For the sake of this example, let’s say that we want to convert 2019-04-01 10:32:00 into an Epoch timestamp.
strtotime
To do this in PHP, we can use the strtotime function like so:
//Our date string. The format is Y-m-d H:i:s $date = '2019-04-01 10:32:00'; //Convert it into a Unix timestamp using strtotime. $timestamp = strtotime($date); //Print it out. echo $timestamp;
If you run the example above, you will see that 1554107520 is printed out onto the page. This is because 1554107520 passed between the Epoch time and 10:32AM on the 1st of April, 2019.
Note that the strtotime function will return a boolean FALSE value if the conversion fails.
Using the DateTime object.
If you prefer using OOP and the DateTime object, then you can do the following:
//Our date string. $date = '2019-04-01 10:32:00'; //Create a new DateTime object using the date string above. $dateTime = new DateTime($date); //Format it into a Unix timestamp. $timestamp = $dateTime->format('U'); //Print it out. echo $timestamp;
As you can see, it’s pretty similar to the strtotime approach. In the case above, we simply converted the date by passing the “U” format character into the DateTime “format” method.
Note that if you leave out the exact time, PHP will default to midnight:
//Create a DateTime object. $dateTime = new DateTime('2019-04-01'); //Format it into a Unix timestamp. echo $dateTime->format('U');
The above example will output “1554069600”, which is the Unix timestamp for midnight on the 1st of April, 2019.
By the way, in order to get the current timestamp, you can simply call PHP’s time function like so:
echo time();
That’s it! Hopefully, you found this guide useful!