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.
To do this in PHP, we can use the strtotime function like so:
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:
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:
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:
That’s it! Hopefully, you found this guide useful!