How to Convert DateTime to Timestamp in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hey Guys,

Here, I will show you php convert date to timestamp. In this article, we will implement a php convert datetime to timestamp. This article goes in detailed on php date to timestamp . you can understand a concept of how to convert date to timestamp in php.

In this example, i will give you following two simple examples with output to convert datetime into timestamp using php. so, let's see the one by one example:

Example 1: using DateTime()

In PHP, you can convert a DateTime object to a Unix timestamp using the "getTimestamp" method or by using the "format" method to get the timestamp string and then converting it to an integer. Here are examples of both methods:

index.php

<?php

/* Create a DateTime object */

$date = new DateTime('2023-01-01 12:00:00');

/* Get the timestamp using getTimestamp method */

$timestamp = $date->getTimestamp();

/* Output the timestamp */

echo $timestamp;

?>

Output:

1672574400

Example 2: using strtotime()

If you want to convert a DateTime object to a Unix timestamp without using the "DateTime" class in PHP, you can use the "strtotime" function. Here's an example:

index.php

<?php

/* Your DateTime string */

$dateString = '2023-01-01 12:00:00';

/* Convert DateTime string to timestamp */

$timestamp = strtotime($dateString);

/* Output the timestamp */

echo $timestamp;

?>

Output:

1672574400

In this example, replace "$dateString" with your actual DateTime string. The "strtotime" function parses the provided date/time string and returns a Unix timestamp.

Keep in mind that this approach has some limitations, and it may not work correctly in all scenarios, especially if your DateTime string format is not recognized by "strtotime". The "DateTime" class is generally recommended for more robust and reliable handling of date and time in PHP. If possible, consider using DateTime for better control and consistency.

I hope it can help you...

Tags :
Shares