PHP:将负时间戳转换为日期 [英] PHP: Convert negative timestamp to date

查看:51
本文介绍了PHP:将负时间戳转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个负时间戳,我想将其转换为可读的日期格式.

I have a negative timestamp and I wanted to convert it to a readable date format.

$timestamp = -1861945262080;

如果我使用 date("d-m-Y", $timestamp),它只会输出 12-08-2035.

If I use date("d-m-Y", $timestamp), it will just output 12-08-2035.

推荐答案

以下代码将您的 UNIX 时间戳转换为有效的日期-月-年.但是,传递相当大的负 unix 时间戳会产生意想不到的结果,如下所示.

The below piece of code transforms your UNIX timestamp to a valid date-month-year. However , passing pretty large negative unix timestamps can produce unexpected results as shown below.

 <?php
    $dt = new DateTime();
    $dt->setTimestamp(-1861945262080); //<--- Pass a UNIX TimeStamp
    echo $dt->format('d-m-Y');

输出:

12-08-2035

但是,您仍然可以将负时间戳传递给上述事物.考虑一下 wikipedia 的摘录.

However, you still can pass negative timestamps to the above thing. Consider this excerpt from wikipedia.

Unix 时代的 Unix 时间数为零,并且增加了自纪元以来每天正好 86400.因此 2004-09-16T00:00:00Z,纪元后的 12677 天,由 Unix 时间数字表示12677 × 86400 = 1095292800.这可以从epoch 也是,使用负数;因此 1957-10-04T00:00:00Z, 4472纪元前的天数,由 Unix 时间数表示 -4472 ×86400 = -386380800.

The Unix time number is zero at the Unix epoch, and increases by exactly 86400 per day since the epoch. Thus 2004-09-16T00:00:00Z, 12677 days after the epoch, is represented by the Unix time number 12677 × 86400 = 1095292800. This can be extended backwards from the epoch too, using negative numbers; thus 1957-10-04T00:00:00Z, 4472 days before the epoch, is represented by the Unix time number -4472 × 86400 = -386380800.

那么让我们将 -386380800 传递给上面的代码.

So let's pass the -386380800 to the above code.

 <?php
    $dt = new DateTime();
    $dt->setTimestamp(-386380800); //<--- Pass a UNIX TimeStamp
    echo $dt->format('d-m-Y');

输出:

04-10-1957

这是根据来源的预期输出.

which is the expected output as per the sources.

这篇关于PHP:将负时间戳转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆