PHP基于DateTime类解决Unix时间戳与日期互转问题【针对1970年前及2038年后时间戳】

yipeiwu_com7年前PHP代码库

本文实例讲述了PHP基于DateTime类解决Unix时间戳与日期互转问题。分享给大家供大家参考,具体如下:

这个问题主要在32位的系统下出现,64位的不存在这样的问题。php 5.2+提供了DateTime类来处理这样的问题,参考方案如下(请注意时区的处理):

//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 '<br>';
echo unixtime_to_date(date_to_unixtime("1900-1-31 00:00:00")); //输出1900-01-31 00:00:00

PS:这里再为大家推荐几款时间及日期相关工具供大家参考使用:

在线日期/天数计算器:
http://tools.jb51.net/jisuanqi/date_jisuanqi

在线日期计算器/相差天数计算器:
http://tools.jb51.net/jisuanqi/datecalc

在线日期天数差计算器:
http://tools.jb51.net/jisuanqi/onlinedatejsq

Unix时间戳(timestamp)转换工具:
http://tools.jb51.net/code/unixtime

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php日期与时间用法总结》、《PHP数组(Array)操作技巧大全》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP实现查询两个数组中不同元素的方法

本文实例讲述了PHP实现查询两个数组中不同元素的方法。分享给大家供大家参考,具体如下: <?php $a = array( "max_allow_dialogs...

php中file_get_contents()函数用法实例

我们先来看一下php中的 file_get_contents()函数的语法 string file_get_contents(string $ filename,bool $ inc...

PHP警告Cannot use a scalar value as an array的解决方法

看到php的错误日志里有些这样的提示: [27-Aug-2011 22:26:12] PHP Warning: Cannot use a scalar value as an array...

PHP实现广度优先搜索算法(BFS,Broad First Search)详解

本文实例讲述了PHP实现广度优先搜索算法。分享给大家供大家参考,具体如下: 广度优先搜索的算法思想 Breadth-FirstTraversal 广度优先遍历是连通图的一种遍历策略。因为...

Windows中安装Apache2和PHP4权威指南

Apache 2和PHP是创建交互式网站的流行方案,而且成本很低。在Windows中安装Apache 2是一件轻而易举的事情,但要使PHP 4与Apache...