【问题标题】:Find out how long ago something happened找出多久以前发生的事情
【发布时间】:2013-04-08 13:41:23
【问题描述】:

我有一个网页,它在 UNIX 中记录上次查看数据库字段的时间。 我想制作一份报告,说明上次查看此页面是多少天前。我在 PHP 中这样做

我该如何解决这个问题?目前,我使用 gmdate("M D Y ", $UNIXTIMESTAMPFIELD) 显示上次访问该字段的时间,但我想显示的不是上次访问的日期,而是类似

23 天前

谢谢

基兰

【问题讨论】:

  • 你可以从现在的时刻 (date()) 中减去这个日期时间值,然后除以 60 得到分钟,60*60 得到小时,24*60*60 得到天等等。
  • @Voitcus,基于秒的计算会让你在白天节省和日历系统的其他怪癖上绊倒,这真是个坏主意。
  • @complex857:你刚刚从我嘴里说出来的话。

标签: php unix-timestamp


【解决方案1】:

如果您使用的是 PHP5.3 或更高版本,这很容易。使用DateInterval对象,可以理解unix时间戳,轻松输出差异。

您可以做的非常非常简单。假设您的时间戳是 $TS1、$TS2。

第 1 步:为每个对象创建 DateTime 对象:

$DT1 = new DateTime("@{$TS1}");
$DT2 = new DateTime("@{$TS2}");

第 2 步:区分它们

$diff = $DT1->diff($DT2);

第 3 步:打印内容!

echo "Days: ".$diff->d;

这会自动考虑时区设置等。它还允许您在需要时轻松地从日期时间对象中减去。

【讨论】:

  • 好答案。但请注意,如果您使用 UNIX 时间戳,则必须使用 DateTime::setTimestamp() 来初始化 DateTime 对象。您不能将它们传递给构造函数
  • @hek2mgl 实际上,你可以,如果你在时间戳前面加上@ 在构造函数中查看note for timezone
  • 感谢您提供此信息!不幸的是只能投票一次;)
【解决方案2】:

差异显然是$diff = time() - $UNIXTIMESTAMPFIELD(现在事件)。不是你只需要正确格式化:

function time_diff_to_human($seconds){
    // For seconds
    if( $seconds < 60){
        if( $seconds == 1){
            return "a second ago"
        }
        return sprintf( "%d seconds ago", $seconds);
    }

    // Minutes
    $minutes = round( $seconds/60);
    if( $minutes < 60){
        if( $minutes == 1){
            return "a minute ago"
        }
        return sprintf( "%d minutes ago", $minutes);
    }

    // Hours
    $hours = round( $minutes/60);
    if( $hours < 24){
        if( $hours == 1){
            return "last hour"
        }
        return sprintf( "%d hours", $hours);
    }

    // Add some formatting to days
    $days = $months/24;
    if( $days < 31){
        if( $days == 1){
            return 'yesterday';
        }
        return sprintf( "%d days", $days);
    }

    // Approx months
    $months = round( $days/30);
    if( $months < 12){
        if( $months == 1){
            return "last month"
        }
        return sprintf( "%d months", $months);
    }

    // And finally years, note that they are calculated from days
    $years = round( $days/365.4);
    if( $years == 1){
        return "last year"
    }
    return sprintf( "%d years", $years);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2011-03-08
    • 1970-01-01
    • 2010-11-24
    • 2014-06-18
    相关资源
    最近更新 更多