PASSWORD RESET

Your destination for complete Tech news

PHP

How to convert a date to timestamp in PHP?

396 0
< 1 min read

To convert a date to a timestamp in PHP, you can use the strtotime function. This function parses a date string and returns the corresponding timestamp.

Here’s an example of how to use the strtotime function:

$date = '2022-12-25';
$timestamp = strtotime($date);

// $timestamp is now the Unix timestamp for the date "2022-12-25 00:00:00"

The strtotime function can parse a wide range of date formats, including ISO-8601 formats, MySQL formats, and other common formats. You can also use relative dates such as “next Tuesday” or “3 weeks ago”.

If the date string is invalid or cannot be parsed, the strtotime function returns false.

You can also use the DateTime class to convert a date to a timestamp. The DateTime class provides more features and flexibility than the strtotime function, but it may be slower and more complex to use.

Here’s an example of how to use the DateTime class to convert a date to a timestamp:

$date = new DateTime('2022-12-25');
$timestamp = $date->getTimestamp();

// $timestamp is now the Unix timestamp for the date "2022-12-25 00:00:00"

Note that the DateTime class represents dates in the default timezone of the server. If you need to work with dates in a different timezone, you can use the setTimezone method to set the desired timezone.

For Example:

$date = new DateTime('2022-12-25');
$date->setTimezone(new DateTimeZone('Europe/Paris'));
$timestamp = $date->getTimestamp();

// $timestamp is now the Unix timestamp for the date "2022-12-25 00:00:00" in the Paris timezone

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.