How to Convert Datetime into Milliseconds in PHP?

By Hardik Savani December 26, 2023 Category : PHP

Hi Friends,

This detailed guide will cover php convert date to milliseconds. In this article, we will implement a php convert datetime to milliseconds. This example will help you php date to milliseconds . you will learn how to convert date to milliseconds in php. Let's get started with how to convert datetime into milliseconds in php.

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

Example 1: using DateTime()

In PHP, you can convert a date to milliseconds using the DateTime class. Here's an example:

index.php

<?php

/* Your date string */

$dateString = "2023-01-01 12:34:56";

/* Create a DateTime object */

$dateTime = new DateTime($dateString);

/* Get the timestamp in seconds */

$timestampInSeconds = $dateTime->getTimestamp();

/* Convert seconds to milliseconds */

$timestampInMilliseconds = $timestampInSeconds * 1000;

/* Output the result */

echo "Date in milliseconds: " . $timestampInMilliseconds;

?>

Output:

Date in milliseconds: 1672576496000

In this example, replace $dateString with your actual date string. The DateTime class is used to create a DateTime object, and getTimestamp() is used to get the timestamp in seconds. Then, it's multiplied by 1000 to convert it to milliseconds.

Keep in mind that the result will be based on the server's timezone if not explicitly set in the DateTime object. If you want to set a specific timezone, you can use the setTimezone() method on the DateTime object.

Example 2: using strtotime()

If you prefer not to use the DateTime class, you can achieve the conversion to milliseconds using the strtotime function, which converts a human-readable date string to a Unix timestamp. Here's an example:

index.php

<?php

/* Your date string */

$dateString = "2023-01-01 12:34:56";

/* Convert date string to timestamp in seconds */

$timestampInSeconds = strtotime($dateString);

/* Convert seconds to milliseconds */

$timestampInMilliseconds = $timestampInSeconds * 1000;

/* Output the result */

echo "Date in milliseconds: " . $timestampInMilliseconds;

?>

Output:

Date in milliseconds: 1672576496000

In this example, replace $dateString with your actual date string. The strtotime function parses the date string and returns a Unix timestamp, which is then multiplied by 1000 to convert it to milliseconds.

Keep in mind that strtotime uses the system timezone. If you need to work with a specific timezone, you might still want to consider using the DateTime class with the setTimezone method or use the DateTimeImmutable class, which is more predictable in terms of timezones.

I hope it can help you...

Tags :
Shares