我正在尝试转换格式为2009-09-12 20:57:19的时间戳,并将其转换为3分钟前用PHP。

我找到了一个有用的脚本来做这件事,但我认为它正在寻找一种不同的格式来用作时间变量。我想修改的脚本与此格式的工作是:

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;
    }

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

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

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


当前回答

我不知道为什么还没有人提到碳。

https://github.com/briannesbitt/Carbon

这实际上是php dateTime的扩展(这里已经使用了),它有:diffForHumans方法。所以你所需要做的就是:

$dt = Carbon::parse('2012-9-5 23:26:11.123789');
echo $dt->diffForHumans();

更多例子:http://carbon.nesbot.com/docs/#api-humandiff

这个解决方案的优点:

它适用于未来的日期,并将在2个月等时间内返回。 你可以使用本地化来获取其他语言,多元化也很好 如果你开始用碳来做其他事情,处理日期就会变得非常容易。

其他回答

这是我的解决方案,请检查并根据您的要求修改

function getHowLongAgo($date, $display = array('Year', 'Month', 'Day', 'Hour', 'Minute', 'Second'), $ago = '') {
        date_default_timezone_set('Australia/Sydney');
        $timestamp = strtotime($date);
        $timestamp = (int) $timestamp;
        $current_time = time();
        $diff = $current_time - $timestamp;

        //intervals in seconds
        $intervals = array(
            'year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60
        );

        //now we just find the difference
        if ($diff == 0) {
            return ' Just now ';
        }

        if ($diff < 60) {
            return $diff == 1 ? $diff . ' second ago ' : $diff . ' seconds ago ';
        }

        if ($diff >= 60 && $diff < $intervals['hour']) {
            $diff = floor($diff / $intervals['minute']);
            return $diff == 1 ? $diff . ' minute ago ' : $diff . ' minutes ago ';
        }

        if ($diff >= $intervals['hour'] && $diff < $intervals['day']) {
            $diff = floor($diff / $intervals['hour']);
            return $diff == 1 ? $diff . ' hour ago ' : $diff . ' hours ago ';
        }

        if ($diff >= $intervals['day'] && $diff < $intervals['week']) {
            $diff = floor($diff / $intervals['day']);
            return $diff == 1 ? $diff . ' day ago ' : $diff . ' days ago ';
        }

        if ($diff >= $intervals['week'] && $diff < $intervals['month']) {
            $diff = floor($diff / $intervals['week']);
            return $diff == 1 ? $diff . ' week ago ' : $diff . ' weeks ago ';
        }

        if ($diff >= $intervals['month'] && $diff < $intervals['year']) {
            $diff = floor($diff / $intervals['month']);
            return $diff == 1 ? $diff . ' month ago ' : $diff . ' months ago ';
        }

        if ($diff >= $intervals['year']) {
            $diff = floor($diff / $intervals['year']);
            return $diff == 1 ? $diff . ' year ago ' : $diff . ' years ago ';
        }
    }

谢谢

function humanTiming ($time)
        {

            $time = time() - $time; // to get the time since that moment
            $time = ($time<1)? 1 : $time;
            $tokens = array (
                31536000 => 'year',
                2592000 => 'month',
                604800 => 'week',
                86400 => 'day',
                3600 => 'hour',
                60 => 'minute',
                1 => 'second'
            );

            foreach ($tokens as $unit => $text) {
                if ($time < $unit) continue;
                $numberOfUnits = floor($time / $unit);
                return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
            }

        }

echo humanTiming( strtotime($mytimestring) );

这里的许多解决方案没有考虑舍入。例如:

事件发生在两天前的下午3点。如果您在下午2点查看,它会显示在一天前。如果你在下午4点查看,它会显示两天前。

如果你使用unix时间,这有助于:

// how long since event has passed in seconds
$secs = time() - $time_ago;

// how many seconds in a day
$sec_per_day = 60*60*24;

// days elapsed
$days_elapsed = floor($secs / $sec_per_day);

// how many seconds passed today
$today_seconds = date('G')*3600 + date('i') * 60 + date('s');

// how many seconds passed in the final day calculation
$remain_seconds = $secs % $sec_per_day;

if($today_seconds < $remain_seconds)
{
    $days_elapsed++;
}

echo 'The event was '.$days_ago.' days ago.';

如果你担心闰秒和夏时制,这并不完美。

我想有一个荷兰版本,支持单复数。仅仅在结尾加一个“s”是不够的,我们用的是完全不同的词,所以我重写了这篇文章的顶部答案。

这将导致:

2年1个月2周1天1分2秒

or

1年2个月1周2天1分1秒

    public function getTimeAgo($full = false){

    $now = new \DateTime;
    $ago = new \DateTime($this->datetime());
    $diff = $now->diff($ago);

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

    $string = array(
        'y' => 'jaren',
        'm' => 'maanden',
        'w' => 'weken',
        'd' => 'dagen',
        'h' => 'uren',
        'i' => 'minuten',
        's' => 'seconden',
    );
    $singleString = array(
        'y' => 'jaar',
        'm' => 'maand',
        'w' => 'week',
        'd' => 'dag',
        'h' => 'uur',
        'i' => 'minuut',
        's' => 'seconde',
    );
    // M.O. 2022-02-11 I rewrote this function to support dutch singles and plurals. Added some docs for next programmer to break his brain :)
    // For each possible notation, if corresponding value of current key is true (>1) otherwise remove its key/value from array
    // If the value from current key is 1, use value from $singleString array. Otherwise use value from $string array
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            if($diff->$k == 1){
                $v = $diff->$k . ' ' . $singleString[$k];
            } else {
                $v = $diff->$k . ' ' . $v;
            }
        } else {
            if($diff->$k == 1){
                unset($singleString[$k]);
            } else {
                unset($string[$k]);
            }
        }
    }

    // If $full = true, print all values.
    // Values have already been filtered with foreach removing keys that contain a 0 as value
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . '' : 'zojuist';
}

你应该先测试一下,因为我不是一个优秀的程序员:)

我发现结果如下:

1年2个月0天0小时53分1秒

正因为如此,我实现了一个尊重复数的函数,删除空值,并有可能缩短输出:

function since($timestamp, $level=6) {
    global $lang;
    $date = new DateTime();
    $date->setTimestamp($timestamp);
    $date = $date->diff(new DateTime());
    // build array
    $since = array_combine(array('year', 'month', 'day', 'hour', 'minute', 'second'), explode(',', $date->format('%y,%m,%d,%h,%i,%s')));
    // remove empty date values
    $since = array_filter($since);
    // output only the first x date values
    $since = array_slice($since, 0, $level);
    // build string
    $last_key = key(array_slice($since, -1, 1, true));
    $string = '';
    foreach ($since as $key => $val) {
        // separator
        if ($string) {
            $string .= $key != $last_key ? ', ' : ' ' . $lang['and'] . ' ';
        }
        // set plural
        $key .= $val > 1 ? 's' : '';
        // add date value
        $string .= $val . ' ' . $lang[ $key ];
    }
    return $string;
}

看起来好多了:

1年2个月53分1秒

可以选择使用$level = 2来缩短它,如下所示:

1年2个月

如果你只需要它的英文版本,就删除$lang部分,或者编辑这个翻译来满足你的需要:

$lang = array(
    'second' => 'Sekunde',
    'seconds' => 'Sekunden',
    'minute' => 'Minute',
    'minutes' => 'Minuten',
    'hour' => 'Stunde',
    'hours' => 'Stunden',
    'day' => 'Tag',
    'days' => 'Tage',
    'month' => 'Monat',
    'months' => 'Monate',
    'year' => 'Jahr',
    'years' => 'Jahre',
    'and' => 'und',
);