1

我需要找到一种方法来找出如何以秒为单位生成时间戳,该时间戳表示 1970 年之前的日期与当前时间之间的间隔。

X人生日1969-01-02

当天 2013-08-23

我试过了

<?php
$then = new DateTime("1969-01-02");
$age = $then->getTimestamp();
?>

给我一个负时间戳,直到 1970 年。

我也做了一个日期差异

<?php
    $then = new DateTime("1969-01-02");
    $now = new DateTime("now");
    $age = $then->diff($now);
?>

但我不知道如何将日期差异转换为我可以使用的秒时间戳。请问有什么帮助吗?

我问的原因是,在 1970 年之后的日期相对于现在执行时间戳时,它可以正常工作并给出预期的输出。但是,如果某人的生日在 1970 年之前,它只会计算他们出生日期的时间戳,直到 1970 年,这是完全不准确的。因此,我需要找到一种方法来获取出生日期在 1970 年之前的人的年龄时间戳(以秒为单位)。

4

1 回答 1

0

这是预期的行为。

UNIX timestamp是自以来的秒数Jan 1 1970(不考虑闰秒)。对于在此之前的日期,它将return是一个负数。

是的,如果你想计算years, months and days然后试试这个,

<?php
    $then = new DateTime("1969-01-02");
    $now = new DateTime('now');
    $age = $then->diff($now);
    echo $age->format('%Y years, %m months,%d days');
?>

更新,

<?php
    $then = strtotime("1969-01-02");
    $now = strtotime('now');

    $age=$now-$then;
    // Above is your final time stamp, created by the difference of two dates

    $diff = abs($age);
    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
    printf("%d years, %d months, %d days\n", $years, $months, $days);
    // Outputs-> 44 years, 8 months, 4 days 
?>
于 2013-08-23T11:03:46.060 回答