How to convert date to timestamp in PHP example

How to convert date to timestamp in PHP example

In this article lets understand how to convert date to timestamp in PHP example.

There are two methods to do so as below :

  • strtotime()
  • DateTime

This methods allows to covert date to Unix timestamp. Lets check them with example :

1. Using strtotime()

This function converts string date format to Unix timestamp, this is built in php function. Check syntax :


$dateString = "2023-07-26 15:30:00";
$timestamp = strtotime($dateString);

echo $timestamp;

// Output : 1679914200

2. Using DateTime class :

DateTime provides object oriented way to get Unix timestamp from string.


$dateString = "2023-07-26 15:30:00";
$dateTimeObj = new DateTime($dateString);
$timestamp = $dateTimeObj->getTimestamp();

echo $timestamp;
// Output : 1679914200

Here we are using getTimestamp method from DateTime Class which will do the job.

Both methods provides the same result. Depending on you need you can use any one of them.

That’s it on how to convert date to timestamp in PHP example.

See other articles on PHP here.