Home  >  Article  >  Backend Development  >  How to convert php time to unix timestamp

How to convert php time to unix timestamp

PHPz
PHPzOriginal
2023-03-29 11:31:39691browse

How to use PHP to convert time to Unix timestamp

Unix timestamp is a time representation method used in the Unix operating system. It represents since January 1, 1970 00:00:00 UTC The number of seconds since (Coordinated Universal Time). PHP provides some built-in functions that can easily convert time to Unix timestamp. This article will introduce how to use these functions.

  1. Use the time() function to obtain the Unix timestamp of the current time

In PHP, use the time() function to obtain the Unix timestamp of the current time. Specific usage Here's how:

$timestamp = time();

In the above example, the $timestamp variable will contain the Unix timestamp of the current time.

  1. Use the strtotime() function to convert a time string to a Unix timestamp

The strtotime() function can convert a string containing date and time to a Unix time stamp. The date and time formats it supports are very flexible. For example, the following formats can be used:

  • yyyy-mm-dd (for example, 2022-01-01)
  • yyyy/mm/dd ( For example, 2022/01/01)
  • yyyy year mm month dd day (for example January 01, 2022)
  • hh:mm:ss (for example 12:00:00)
  • hh:mm:ss am/pm (for example 12:00:00 am)
  • yyyy-mm-dd hh:mm:ss (for example 2022-01-01 12:00:00)

For example, the following code will convert a date and convert it to a Unix timestamp:

$date = '2022-01-01';
$timestamp = strtotime($date);

In the above example, the $timestamp variable will contain the Unix date of January 1, 2022 timestamp.

  1. Use the DateTime class to convert a date-time object into a Unix timestamp

Use PHP's DateTime class to create a date-time object that can easily be used for date and time Calculate time and convert it to Unix timestamp. For example, the following code will create a datetime object and convert it to a Unix timestamp:

$dateString = '2022-01-01 12:00:00';
$date = new DateTime($dateString);
$timestamp = $date->getTimestamp();

In the above example, the $timestamp variable will contain the Unix timestamp of the datetime object.

  1. Summary

In PHP, you can use the time() function to get the Unix timestamp of the current time, and use the strtotime() function to convert the time string to Unix time stamp, or use the DateTime class to convert a datetime object to a Unix timestamp. Just choose the appropriate method according to actual needs.

The above is the detailed content of How to convert php time to unix timestamp. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn