在 PHP 中将时间戳转换为时间前,例如 1 天前、2 天前......

2022-01-13 00:00:00 timestamp php

我正在尝试转换格式为 2009-09-12 20:57:19 的时间戳,并使用 PHP 将其转换为类似于 3 minutes ago 的格式.

I am trying to convert a timestamp of the format 2009-09-12 20:57:19 and turn it into something like 3 minutes ago with PHP.

我找到了一个有用的脚本来执行此操作,但我认为它正在寻找一种不同的格式来用作时间变量.我要修改以使用这种格式的脚本是:

I found a useful script to do this, but I think it's looking for a different format to be used as the time variable. The script I'm wanting to modify to work with this format is:

function _ago($tm,$rcs = 0) {
    $cur_tm = time(); 
    $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
        $no = floor($no);
        if($no <> 1)
            $pds[$v] .='s';
        $x = sprintf("%d %s ",$no,$pds[$v]);
        if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
            $x .= time_ago($_tm);
        return $x;
    }

我认为在前几行中,脚本试图做一些看起来像这样的事情(不同的日期格式数学):

I think on those first few lines the script is trying to do something that looks like this (different date format math):

$dif = 1252809479 - 2009-09-12 20:57:19;

如何将我的时间戳转换为那种(unix?)格式?

How would I go about converting my timestamp into that (unix?) format?

推荐答案

使用示例:

echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('@1367367755'); # timestamp input
echo time_elapsed_string('2013-05-01 00:22:35', true);

输入可以是任何支持的日期和时间格式..p>

输出:

4 months ago
4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago

功能:

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

相关文章