博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

PHP Y2K38 (2038年) 问题

Posted on 2019-11-19 11:58  PHP-张工  阅读(406)  评论(0编辑  收藏  举报

PHP 的 strtotime('2100-01-01'); 转换失败;经查询是因为32位系统的 Y2K38问题;

Y2K38 问题:当时间大于 2038年01月19日03:14:07 时,strtotimetimedate函数在32系统下(PHP的版本)将导致转换失败;

问题解决办法:使用 new DateTime(); 来做时间转换处理;代码如下:

<?php

/**
 * 替换系统 strtotime, Y2K38问题
 */
function _strtotime($dt = null, $modify = '')
{
    $d = null;
    if (empty($dt))
    {
        $d = new \DateTime();
    }
    else if (\is_numeric($dt))
    {
        $d = new \DateTime('@' . $dt);
    }
    else
    {
        $d = new \DateTime($dt);
    }

    $d -> setTimeZone(new \DateTimeZone('PRC'));
    if ($modify != '')
    {
        $d -> modify($modify);
    }

    return $d -> format('U');
}

/**
 * 替换系统 date, Y2K38问题
 */
function _date($format = 'Y-m-d H:i:s', $dt = null)
{
    $d = new \DateTime('@' . _strtotime($dt));
    $d -> setTimeZone(new \DateTimeZone('PRC'));

    return $d -> format($format);
}

// 测试代码
echo _strtotime('2100-01-01') . PHP_EOL; echo _strtotime('2100-01-01', '+10day') . PHP_EOL; echo _date() . PHP_EOL; echo _date('Y-m-d', '2100-01-01') . PHP_EOL; $dt = _strtotime('2100-01-01', '+10day'); echo _date('Y-m-d', $dt) . PHP_EOL; $dt -= 24*3600; echo _date('Y-m-d', $dt) . PHP_EOL;