Home  >  Article  >  Backend Development  >  How to solve the problem of converting Unix timestamp and date in PHP based on DateTime class

How to solve the problem of converting Unix timestamp and date in PHP based on DateTime class

不言
不言Original
2018-06-13 09:34:221601browse

This article mainly introduces PHP's solution to the problem of Unix timestamp and date conversion based on the DateTime class. It uses the DateTime class to solve the problem of displaying and calculating timestamps before 1970 and after 2038. It is very simple and practical, and the code has more Detailed comments are easy to understand. Friends in need can refer to

. This article describes how PHP solves the problem of Unix timestamp and date conversion based on the DateTime class. Share it with everyone for your reference, the details are as follows:

This problem mainly occurs in 32-bit systems, and there is no such problem in 64-bit systems. PHP 5.2 provides the DateTime class to handle such problems. The reference plan is as follows (please pay attention to the processing of time zones):

//1、Unix时间戳转日期
function unixtime_to_date($unixtime, $timezone = 'PRC') {
  $datetime = new DateTime("@$unixtime"); //DateTime类的bug,加入@可以将Unix时间戳作为参数传入
  $datetime->setTimezone(new DateTimeZone($timezone));
  return $datetime->format("Y-m-d H:i:s");
}
//2、日期转Unix时间戳
function date_to_unixtime($date, $timezone = 'PRC') {
  $datetime= new DateTime($date, new DateTimeZone($timezone));
  return $datetime->format('U');
}
echo date_to_unixtime("1900-1-31 00:00:00"); //输出-2206425952
echo &#39;<br>&#39;;
echo unixtime_to_date(date_to_unixtime("1900-1-31 00:00:00")); //输出1900-01-31 00:00:00

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to use php to handle the function of multi-image upload compression

Use html_entity_decode to implement HTML in php Entity Escape

The above is the detailed content of How to solve the problem of converting Unix timestamp and date in PHP based on DateTime class. 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