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

将时间戳转换为PHP中的时间戳,例如1天前、2天前。。。,php,timestamp,Php,Timestamp,我正在尝试转换格式为2009-09-12 20:57:19的时间戳,并使用PHP将其转换为大约3分钟前的格式 我找到了一个有用的脚本来实现这一点,但我认为它正在寻找一种不同的格式来用作时间变量。我想修改脚本以使用此格式: function _ago($tm,$rcs = 0) { $cur_tm = time(); $dif = $cur_tm-$tm; $pds = array('second','minute','hour','day','week','month'

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

我找到了一个有用的脚本来实现这一点,但我认为它正在寻找一种不同的格式来用作时间变量。我想修改脚本以使用此格式:

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

我将如何将时间戳转换为unix?格式化?

您必须获取每个时间戳,并将其转换为Unix时间。例如时间戳,2009-09-12 20:57:19

2008-1970*365+8*30+12*24+20将为您提供自1970年1月1日以来的小时数的粗略估计

取这个数字,乘以60,再加上57,得到分钟数

把它乘以60,再加上19

然而,这将非常粗略和不准确地转换它


有什么原因不能从普通的Unix开始吗?

我对原始函数进行了一些修改,使其在我看来更有用或更符合逻辑

function time_elapsed_string($ptime)
{
    $etime = time() - $ptime;

    if ($etime < 1)
    {
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  'minute',
                                 1  =>  'second'
                );
    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => 'minutes',
                       'second' => 'seconds'
                );

    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
        }
    }
}
// display "X time" ago, $rcs is precision depth
function time_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 = count($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--);
    if ($v < 0)
      $v = 0;
  $_tm = $cur_tm - ($dif % $lngh[$v]);

  $no = ($rcs ? floor($no) : round($no)); // if last denomination, round

  if ($no != 1)
    $pds[$v] .= 's';
  $x = $no . ' ' . $pds[$v];

  if (($rcs > 0) && ($v >= 1))
    $x .= ' ' . $this->time_ago($_tm, $rcs - 1);

  return $x;
}
使用示例: 回音时间(经过字符串“2013-05-01 00:22:35”); 回音时间_经过_字符串'@1367367755';时间戳输入 回音时间经过字符串'2013-05-01 00:22:35',正确; 输入可以是任意的

输出: 4个月前 4个月前 4个月2周3天1小时49分15秒前 功能: 函数时间\u已用\u字符串$datetime,$full=false{ $now=新日期时间; $ago=新日期时间$DateTime; $diff=$now->diff$ago; $diff->w=楼层$diff->d/7; $diff->d-=$diff->w*7; $string=数组 ‘y’=>‘年’, 'm'=>'month', “w”=>“周”, 'd'=>'day', “h”=>“小时”, “i”=>“分钟”, 's'=>'秒', ; foreach$字符串为$k=>&$v{ 如果$diff->$k{ $v=$diff->$k'..$v.$diff->$k>1?'s':; }否则{ 未设置$string[$k]; } } 如果!$full$string=array\U slice$string,则为0,1; 返回$string?内爆“,”,$string.'ago':'just now'; }
这实际上是我找到的一个更好的解决方案。使用jQuery,但是它工作得非常好。它也会像SO和Facebook那样自动刷新,这样你就不必刷新页面就能看到更新

该插件将读取标签中的datetime属性并为您填写

e.g. "4 minutes ago" or "about 1 day ago
只需将日期和时间传递给此函数。它将以时间前的格式为您打印出来


下面是一个非常简单和非常有效的解决方案

function timeElapsed($originalTime){

        $timeElapsed=time()-$originalTime;

        /*
          You can change the values of the following 2 variables 
          based on your opinion. For 100% accuracy, you can call
          php's cal_days_in_month() and do some additional coding
          using the values you get for each month. After all the
          coding, your final answer will be approximately equal to
          mine. That is why it is okay to simply use the average
          values below.
        */
        $averageNumbDaysPerMonth=(365.242/12);
        $averageNumbWeeksPerMonth=($averageNumbDaysPerMonth/7);

        $time1=(((($timeElapsed/60)/60)/24)/365.242);
        $time2=floor($time1);//Years
        $time3=($time1-$time2)*(365.242);
        $time4=($time3/$averageNumbDaysPerMonth);
        $time5=floor($time4);//Months
        $time6=($time4-$time5)*$averageNumbWeeksPerMonth;
        $time7=floor($time6);//Weeks
        $time8=($time6-$time7)*7;
        $time9=floor($time8);//Days
        $time10=($time8-$time9)*24;
        $time11=floor($time10);//Hours
        $time12=($time10-$time11)*60;
        $time13=floor($time12);//Minutes
        $time14=($time12-$time13)*60;
        $time15=round($time14);//Seconds

        $timeElapsed=$time2 . 'yrs ' . $time5 . 'months ' . $time7 . 
                     'weeks ' . $time9 .  'days ' . $time11 . 'hrs '
                     . $time13 . 'mins and ' . $time15 . 'secs.';

        return $timeElapsed;

}
回波时间延迟1201570814

样本输出:


6年4个月3周4天12小时40分钟36秒。

这是我不久前构建的通知模块的解决方案。它返回的输出类似于Facebook的“通知”下拉列表,例如1天前、现在等

public function getTimeDifference($time) {
    //Let's set the current time
    $currentTime = date('Y-m-d H:i:s');
    $toTime = strtotime($currentTime);

    //And the time the notification was set
    $fromTime = strtotime($time);

    //Now calc the difference between the two
    $timeDiff = floor(abs($toTime - $fromTime) / 60);

    //Now we need find out whether or not the time difference needs to be in
    //minutes, hours, or days
    if ($timeDiff < 2) {
        $timeDiff = "Just now";
    } elseif ($timeDiff > 2 && $timeDiff < 60) {
        $timeDiff = floor(abs($timeDiff)) . " minutes ago";
    } elseif ($timeDiff > 60 && $timeDiff < 120) {
        $timeDiff = floor(abs($timeDiff / 60)) . " hour ago";
    } elseif ($timeDiff < 1440) {
        $timeDiff = floor(abs($timeDiff / 60)) . " hours ago";
    } elseif ($timeDiff > 1440 && $timeDiff < 2880) {
        $timeDiff = floor(abs($timeDiff / 1440)) . " day ago";
    } elseif ($timeDiff > 2880) {
        $timeDiff = floor(abs($timeDiff / 1440)) . " days ago";
    }

    return $timeDiff;
}
$time\u appeased=timeAgo$time\u ago//参数$time_ago在时间戳Y-m-dh:i:sformat中。 //函数定义 函数timeAgo$time\u ago { $time\u ago=strottime$time\u ago; $cur_time=时间; $time\u appeased=$cur\u time-$time\u ago; $seconds=$time\u经过的时间; $minutes=round$time_passed/60; $hours=整轮$time\u已用时间/3600; $days=整轮$time\u已用时间/86400; $weeks=整轮$time\u已用时间/604800; $months=round$time_passed/2600640; $years=round$time_passed/31207680; //秒
如果$seconds这是我的解决方案,请检查并根据您的要求进行修改

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 ago($d) {
$ts = time() - strtotime(str_replace("-","/",$d));

        if($ts>315360000) $val = round($ts/31536000,0).' year';
        else if($ts>94608000) $val = round($ts/31536000,0).' years';
        else if($ts>63072000) $val = ' two years';
        else if($ts>31536000) $val = ' a year';

        else if($ts>24192000) $val = round($ts/2419200,0).' month';
        else if($ts>7257600) $val = round($ts/2419200,0).' months';
        else if($ts>4838400) $val = ' two months';
        else if($ts>2419200) $val = ' a month';


        else if($ts>6048000) $val = round($ts/604800,0).' week';
        else if($ts>1814400) $val = round($ts/604800,0).' weeks';
        else if($ts>1209600) $val = ' two weeks';
        else if($ts>604800) $val = ' a week';

        else if($ts>864000) $val = round($ts/86400,0).' day';
        else if($ts>259200) $val = round($ts/86400,0).' days';
        else if($ts>172800) $val = ' two days';
        else if($ts>86400) $val = ' a day';

        else if($ts>36000) $val = round($ts/3600,0).' year';
        else if($ts>10800) $val = round($ts/3600,0).' years';
        else if($ts>7200) $val = ' two years';
        else if($ts>3600) $val = ' a year';

        else if($ts>600) $val = round($ts/60,0).' minute';
        else if($ts>180) $val = round($ts/60,0).' minutes';
        else if($ts>120) $val = ' two minutes';
        else if($ts>60) $val = ' a minute';

        else if($ts>10) $val = round($ts,0).' second';
        else if($ts>2) $val = round($ts,0).' seconds';
        else if($ts>1) $val = ' two seconds';
        else $val = $ts.' a second';


        return $val;
    }

我知道这里有几个答案,但我就是这么想的。这只是按照我回答的原始问题处理MySQL DATETIME值。数组$a需要一些工作。我欢迎对如何改进提出意见。请致电:

回音时间(经过字符串“2014-11-1409:42:28”)

function time_elapsed_string($ptime)
{
    // Past time as MySQL DATETIME value
    $ptime = strtotime($ptime);

    // Current time as MySQL DATETIME value
    $csqltime = date('Y-m-d H:i:s');

    // Current time as Unix timestamp
    $ctime = strtotime($csqltime); 

    // Elapsed time
    $etime = $ctime - $ptime;

    // If no elapsed time, return 0
    if ($etime < 1){
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  'minute',
                                 1  =>  'second'
    );

    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => 'minutes',
                       'second' => 'seconds'
    );

    foreach ($a as $secs => $str){
        // Divide elapsed time by seconds
        $d = $etime / $secs;
        if ($d >= 1){
            // Round to the next lowest integer 
            $r = floor($d);
            // Calculate time to remove from elapsed time
            $rtime = $r * $secs;
            // Recalculate and store elapsed time for next loop
            if(($etime - $rtime)  < 0){
                $etime -= ($r - 1) * $secs;
            }
            else{
                $etime -= $rtime;
            }
            // Create string to return
            $estring = $estring . $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ';
        }
    }
    return $estring . ' ago';
}

再加上另一个选择

虽然我更喜欢DateTime方法发布,但我不喜欢它显示0年等事实

/* 
 * Returns a string stating how long ago this happened
 */

private function timeElapsedString($ptime){
    $diff = time() - $ptime;
    $calc_times = array();
    $timeleft   = array();

    // Prepare array, depending on the output we want to get.
    $calc_times[] = array('Year',   'Years',   31557600);
    $calc_times[] = array('Month',  'Months',  2592000);
    $calc_times[] = array('Day',    'Days',    86400);
    $calc_times[] = array('Hour',   'Hours',   3600);
    $calc_times[] = array('Minute', 'Minutes', 60);
    $calc_times[] = array('Second', 'Seconds', 1);

    foreach ($calc_times AS $timedata){
        list($time_sing, $time_plur, $offset) = $timedata;

        if ($diff >= $offset){
            $left = floor($diff / $offset);
            $diff -= ($left * $offset);
            $timeleft[] = "{$left} " . ($left == 1 ? $time_sing : $time_plur);
        }
    }

    return $timeleft ? (time() > $ptime ? null : '-') . implode(' ', $timeleft) : 0;
}

我使用以下功能已经好几年了。它工作得很好:

function timeDifference($timestamp)
{
    $otherDate=$timestamp;
    $now=@date("Y-m-d H:i:s");

    $secondDifference=@strtotime($now)-@strtotime($otherDate);
    $extra="";
    if ($secondDifference == 2592000) { 
    // months 
    $difference = $secondDifference/2592000; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." month".$extra." ago"; 
}else if($secondDifference > 2592000)
    {$difference=timestamp($timestamp);} 
elseif ($secondDifference >= 604800) { 
    // weeks 
    $difference = $secondDifference/604800; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." week".$extra." ago"; 
} 
elseif ($secondDifference >= 86400) { 
    // days 
    $difference = $secondDifference/86400; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." day".$extra." ago"; 
} 
elseif ($secondDifference >= 3600) { 
    // hours 

    $difference = $secondDifference/3600; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." hour".$extra." ago"; 
} 
elseif ($secondDifference < 3600) { 
    // hours 
    // for seconds (less than minute)
    if($secondDifference<=60)
    {       
        if($secondDifference==0)
        {
            $secondDifference=1;
        }
        if ($secondDifference>1) { $extra="s"; }
        $difference = $secondDifference." second".$extra." ago"; 

    }
    else
    {

$difference = $secondDifference/60; 
        if ($difference>1) { $extra="s"; }else{$extra="";}
        $difference = round($difference,0); 
        $difference = $difference." minute".$extra." ago"; 
    }
} 

$FinalDifference = $difference; 
return $FinalDifference;
}
使用:

echo elapsed_time('2016-05-09 17:00:00'); // 18 saat 8 dakika önce yazıldı.
功能:

function elapsed_time($time){// Nekadar zaman geçmiş

        $diff = time() - strtotime($time); 

        $sec = $diff;
        $min = floor($diff/60);
        $hour = floor($diff/(60*60));
        $hour_min = floor($min - ($hour*60));
        $day = floor($diff/(60*60*24));
        $day_hour = floor($hour - ($day*24));
        $week = floor($diff/(60*60*24*7));
        $mon = floor($diff/(60*60*24*7*4));
        $year = floor($diff/(60*60*24*7*4*12));

        //difference calculate to string
        if($sec < (60*5)){
            return 'şimdi yazıldı.';
        }elseif($min < 60){
            return 'biraz önce yazıldı.';
        }elseif($hour < 24){
            return $hour.' saat '.$hour_min.' dakika önce yazıldı.';
        }elseif($day < 7){
            if($day_hour!=0){$day_hour=$day_hour.' saat ';}else{$day_hour='';}
            return $day.' gün '.$day_hour.'önce yazıldı.';
        }elseif($week < 4){
            return $week.' hafta önce yazıldı.';
        }elseif($mon < 12){
            return $mon.' ay önce yazıldı.';
        }else{
            return $year.' yıl önce yazıldı.';
        }
    }

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

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

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

此解决方案的优点:

它适用于未来日期,并将在2个月内返回。 您可以使用本地化来获得其他语言,而多元化工作得很好 如果你开始在其他事情上使用碳元素,那么处理日期将变得前所未有的简单。
上面的答案稍加修改:

  $commentTime = strtotime($whatever)
  $today       = strtotime('today');
  $yesterday   = strtotime('yesterday');
  $todaysHours = strtotime('now') - strtotime('today');

private function timeElapsedString(
    $commentTime,
    $todaysHours,
    $today,
    $yesterday
) {
    $tokens = array(
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    $time = time() - $commentTime;
    $time = ($time < 1) ? 1 : $time;
    if ($commentTime >= $today || $commentTime < $yesterday) {
        foreach ($tokens as $unit => $text) {
            if ($time < $unit) {
                continue;
            }
            if ($text == 'day') {
                $numberOfUnits = floor(($time - $todaysHours) / $unit) + 1;
            } else {
                $numberOfUnits = floor(($time)/ $unit);
            }
            return $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '') . ' ago';
        }
    } else {
        return 'Yesterday';
    }
}

我做了这个,它工作得很好,它既适用于unix时间戳,如1470919932,也适用于格式化时间,如16-08-11 14:53:30

它可以帮你检查一下

   function calculate_time_span($seconds)
{  
 $year = floor($seconds /31556926);
$months = floor($seconds /2629743);
$week=floor($seconds /604800);
$day = floor($seconds /86400); 
$hours = floor($seconds / 3600);
 $mins = floor(($seconds - ($hours*3600)) / 60); 
$secs = floor($seconds % 60);
 if($seconds < 60) $time = $secs." seconds ago";
 else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
 else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
 else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
 else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
 else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
 else $time = ($year==1)? $year." year ago":$year." years ago";
return $time; 
}  
  $seconds = time() - strtotime($post->post_date); 
echo calculate_time_span($seconds); 

我发现结果如下:

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',
);

我试过这个,效果很好

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-10');
$difference = $datetime1->diff($datetime2);
echo formatOutput($difference);

function formatOutput($diff){
    /* function to return the highrst defference fount */
    if(!is_object($diff)){
        return;
    }

    if($diff->y > 0){
        return $diff->y .(" year".($diff->y > 1?"s":"")." ago");
    }

    if($diff->m > 0){
        return $diff->m .(" month".($diff->m > 1?"s":"")." ago");
    }

    if($diff->d > 0){
        return $diff->d .(" day".($diff->d > 1?"s":"")." ago");
    }

    if($diff->h > 0){
        return $diff->h .(" hour".($diff->h > 1?"s":"")." ago");
    }

    if($diff->i > 0){
        return $diff->i .(" minute".($diff->i > 1?"s":"")." ago");
    }

    if($diff->s > 0){
        return $diff->s .(" second".($diff->s > 1?"s":"")." ago");
    }
}
请检查此链接以供参考


谢谢!祝你玩得开心。

这就是我要的。这是Abbbas khan帖子的修改版本:

<?php

  function calculate_time_span($post_time)
  {  
  $seconds = time() - strtotime($post);
  $year = floor($seconds /31556926);
  $months = floor($seconds /2629743);
  $week=floor($seconds /604800);
  $day = floor($seconds /86400); 
  $hours = floor($seconds / 3600);
  $mins = floor(($seconds - ($hours*3600)) / 60); 
  $secs = floor($seconds % 60);
  if($seconds < 60) $time = $secs." seconds ago";
  else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
  else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
  else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
  else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
  else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
  else $time = ($year==1)? $year." year ago":$year." years ago";
  return $time; 
  }  



 // uses
 // $post_time="2017-12-05 02:05:12";
 // echo calculate_time_span($post_time); 

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

事件发生在两天前的下午三点。如果您在下午2点检查,它将在一天前显示。如果您在下午4点检查,它将在两天前显示

如果您正在使用unix time,这将有助于:

// 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.';

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

以前的一些语言显示时间存在一些问题,例如阿拉伯语需要3种格式来显示日期。 我在我的项目中使用此功能,希望它们能帮助某人提出任何建议或改进:

/**
 *
 * @param   string $date1 
 * @param   string $date2 the date that you want to compare with $date1
 * @param   int $level  
 * @param   bool $absolute  
 */

function app_date_diff( $date1, $date2, $level = 3, $absolute = false ) {

    $date1 = date_create($date1);   
    $date2 = date_create($date2);
    $diff = date_diff( $date1, $date2, $absolute );

    $d = [
        'invert' => $diff->invert
    ];  

    $diffs = [
        'y' => $diff->y, 
        'm' => $diff->m, 
        'd' => $diff->d
    ];

    $level_reached = 0;

    foreach($diffs as $k=>$v) {

        if($level_reached >= $level) {
            break;
        }

        if($v > 0) {
            $d[$k] = $v;
            $level_reached++;
        }

    }

    return  $d;

}

/**
 * 
 */

function date_timestring( $periods, $format = 'latin', $separator = ',' ) {

    $formats = [
        'latin' => [
            'y' => ['year','years'],
            'm' => ['month','months'],
            'd' => ['day','days']
        ],
        'arabic' => [
            'y' => ['سنة','سنتين','سنوات'],
            'm' => ['شهر','شهرين','شهور'],
            'd' => ['يوم','يومين','أيام']
        ]
    ];

    $formats = $formats[$format];

    $string = [];

    foreach($periods as $period=>$value) {

        if(!isset($formats[$period])) {
            continue;
        }

        $string[$period] = $value.' ';
        if($format == 'arabic') {
            if($value == 2) {
                $string[$period] = $formats[$period][1];
            }elseif($value > 2 && $value <= 10) {
                $string[$period] .= $formats[$period][2];
            }else{
                $string[$period] .= $formats[$period][0];
            }

        }elseif($format == 'latin') {
            $string[$period] .= ($value > 1) ? $formats[$period][1] : $formats[$period][0];
        }

    }

    return implode($separator, $string);


}

function timeago( $date ) {

    $today = date('Y-m-d h:i:s');

    $diff = app_date_diff($date,$today,2);

    if($diff['invert'] == 1) {
        return '';
    }

    unset($diff[0]);

    $date_timestring = date_timestring($diff,'latin');

    return 'About '.$date_timestring;

}

$date1 = date('Y-m-d');
$date2 = '2018-05-14';

$diff = timeago($date2);
echo $diff;

我通常用它来找出当前和通过的日期戳之间的差异

输出

代码


试试这个,我从我的旧代码中找到了它,它显示了正确的结果

function ago($datefrom, $dateto = -1) {
    // Defaults and assume if 0 is passed in that
    // its an error rather than the epoch

    if ($datefrom == 0) {
        return "A long time ago";
    }
    if ($dateto == -1) {
        $dateto = time();
    }

    // Make the entered date into Unix timestamp from MySQL datetime field

    $datefrom = strtotime($datefrom);

    // Calculate the difference in seconds betweeen
    // the two timestamps

    $difference = $dateto - $datefrom;

    // Based on the interval, determine the
    // number of units between the two dates
    // From this point on, you would be hard
    // pushed telling the difference between
    // this function and DateDiff. If the $datediff
    // returned is 1, be sure to return the singular
    // of the unit, e.g. 'day' rather 'days'

    switch (true) {
        // If difference is less than 60 seconds,
        // seconds is a good interval of choice
        case(strtotime('-1 min', $dateto) < $datefrom):
            $datediff = $difference;
            $res = ($datediff == 1) ? $datediff . ' second' : $datediff . ' seconds';
            break;
        // If difference is between 60 seconds and
        // 60 minutes, minutes is a good interval
        case(strtotime('-1 hour', $dateto) < $datefrom):
            $datediff = floor($difference / 60);
            $res = ($datediff == 1) ? $datediff . ' minute' : $datediff . ' minutes';
            break;
        // If difference is between 1 hour and 24 hours
        // hours is a good interval
        case(strtotime('-1 day', $dateto) < $datefrom):
            $datediff = floor($difference / 60 / 60);
            $res = ($datediff == 1) ? $datediff . ' hour' : $datediff . ' hours';
            break;
        // If difference is between 1 day and 7 days
        // days is a good interval                
        case(strtotime('-1 week', $dateto) < $datefrom):
            $day_difference = 1;
            while (strtotime('-' . $day_difference . ' day', $dateto) >= $datefrom) {
                $day_difference++;
            }

            $datediff = $day_difference;
            $res = ($datediff == 1) ? 'yesterday' : $datediff . ' days';
            break;
        // If difference is between 1 week and 30 days
        // weeks is a good interval            
        case(strtotime('-1 month', $dateto) < $datefrom):
            $week_difference = 1;
            while (strtotime('-' . $week_difference . ' week', $dateto) >= $datefrom) {
                $week_difference++;
            }

            $datediff = $week_difference;
            $res = ($datediff == 1) ? 'last week' : $datediff . ' weeks';
            break;
        // If difference is between 30 days and 365 days
        // months is a good interval, again, the same thing
        // applies, if the 29th February happens to exist
        // between your 2 dates, the function will return
        // the 'incorrect' value for a day
        case(strtotime('-1 year', $dateto) < $datefrom):
            $months_difference = 1;
            while (strtotime('-' . $months_difference . ' month', $dateto) >= $datefrom) {
                $months_difference++;
            }

            $datediff = $months_difference;
            $res = ($datediff == 1) ? $datediff . ' month' : $datediff . ' months';

            break;
        // If difference is greater than or equal to 365
        // days, return year. This will be incorrect if
        // for example, you call the function on the 28th April
        // 2008 passing in 29th April 2007. It will return
        // 1 year ago when in actual fact (yawn!) not quite
        // a year has gone by
        case(strtotime('-1 year', $dateto) >= $datefrom):
            $year_difference = 1;
            while (strtotime('-' . $year_difference . ' year', $dateto) >= $datefrom) {
                $year_difference++;
            }

            $datediff = $year_difference;
            $res = ($datediff == 1) ? $datediff . ' year' : $datediff . ' years';
            break;
    }
    return $res;
}
示例:echo ago'2020-06-03 00:14:21 AM'


输出:6天

如果您正在使用PostgreSQL,则它将为您完成以下任务:

const DT_SQL=fetchColumn; }

在sql表中存储为unix时间是否更好?我现在在一个时间戳列上使用mysqls自动时间戳更新,该列可以更改为unix。我只是在学习什么更好?当然。我相信mySQL表的默认类型是您引用的类型,但是Unix时间更实用。您可以始终将其存储为int。您的数据库应具有将日期转换为UNIX格式的功能。在mysql中,您使用UNIX\u时间戳。哦,你通常应该将日期存储为DATETIMEs而不是Int,这样你就可以使用sql函数进行日期操作。你永远不应该在时间上使用数学。你假设一个固定的日历,它不存在。使用php中提供的日期对象处理。。。这里的PHP和jQuery示例可能重复这不是一个好的解决方案,因为它每月使用30天,每年使用12x30天,因此它将返回无效的年数。为什么这有42张赞成票和选定的答案?“从什么时候开始每个月都有30天了?”wassimboy,你能告诉我你为什么要否决我的答案吗。如果我的答案不够好,你可以写一条评论来纠正它,而不必投反对票。你的答案不好,因为它每个月有30天,而不是所有的月份都有30天。阅读上面的其他评论。这是一个返回一般短语的函数,比如这个评论大概是多久前发表的?正如上面提到的,它并不精确,并且有一些下降,但是对于最近的日期,比如说30年,它让我们不精确的人类知道一个事件发生在多久以前。在我的应用程序中运行良好。周部分很好,但总体而言,函数应该更灵活$full应该是字符串输入,以根据需要过滤输出。e、 g.经过的时间\u字符串$datetime,$format=ymw。简单版:关于我最后的评论:将$full=false更改为$level=7,如果$full$string=array\u slice$string,0,1;to$string=array\u slice$string,0,$level;和call time_appeased_string$datetime,2只获取两个最高的日期字符串。我认为这应该适合所有的需要。@mgutt:ofc这个函数不会在用户想要的任何情况下工作;但这是一个很好的起点,在这里,您可以通过最少的修复,获得您所需要的,就像您已经演示过的那样…我在这行$diff->w=floor$diff->d/7获得未知属性w;要修复PHP5.3及以下版本中的未知属性w问题,请将$diff从对象转换为数组,并相应调整代码的其余部分。我在这里发布了修正:任何使用基于固定日历的数学的函数都有根本性的缺陷。使用Date对象,不要计算时间。@chris baker大多数人使用这些类型的函数时,不需要精确到秒。功能在短时间内是准确的,在长时间内,接近就足够了。一个月超过28天,一年超过52周。这真是太棒了。谢谢分享。但在某些情况下,函数返回$numberOfUnits为空,并且只在之前输出。似乎是因为该值小于1秒。在这种情况下,如果你能将它默认为像刚才这样的东西,这将是完美的。最重要的是,这一个适合我。虽然它没有显示去或之前,但
这是双向的。简单修复:如果$date->invert>0{$ending=to go;}否则{$ending=ago;}只需将$ending添加到$string中即可。在这里使用json函数会对性能造成很大影响,完全没有必要。这不是一个好的解决方案。@zombat谢谢您的反馈。我改变了反对爆炸和阵列联合的路线。为什么是全局的?请阅读一些www.PhpTheRightWay.com。完美地工作,并在IST time中显示所需的结果如何使用php时间戳2020-12-19 13:12:58与此插件一起使用即使$time将计算为true,也不应该切换为true?谢谢。我实际上把它转换成了C代码。未定义的函数getCurrentDateTimefyi@gfivehost添加了功能代码,现在可以查看了。
$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',
);
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-10');
$difference = $datetime1->diff($datetime2);
echo formatOutput($difference);

function formatOutput($diff){
    /* function to return the highrst defference fount */
    if(!is_object($diff)){
        return;
    }

    if($diff->y > 0){
        return $diff->y .(" year".($diff->y > 1?"s":"")." ago");
    }

    if($diff->m > 0){
        return $diff->m .(" month".($diff->m > 1?"s":"")." ago");
    }

    if($diff->d > 0){
        return $diff->d .(" day".($diff->d > 1?"s":"")." ago");
    }

    if($diff->h > 0){
        return $diff->h .(" hour".($diff->h > 1?"s":"")." ago");
    }

    if($diff->i > 0){
        return $diff->i .(" minute".($diff->i > 1?"s":"")." ago");
    }

    if($diff->s > 0){
        return $diff->s .(" second".($diff->s > 1?"s":"")." ago");
    }
}
<?php

  function calculate_time_span($post_time)
  {  
  $seconds = time() - strtotime($post);
  $year = floor($seconds /31556926);
  $months = floor($seconds /2629743);
  $week=floor($seconds /604800);
  $day = floor($seconds /86400); 
  $hours = floor($seconds / 3600);
  $mins = floor(($seconds - ($hours*3600)) / 60); 
  $secs = floor($seconds % 60);
  if($seconds < 60) $time = $secs." seconds ago";
  else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
  else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
  else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
  else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
  else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
  else $time = ($year==1)? $year." year ago":$year." years ago";
  return $time; 
  }  



 // uses
 // $post_time="2017-12-05 02:05:12";
 // echo calculate_time_span($post_time); 
// 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.';
/**
 *
 * @param   string $date1 
 * @param   string $date2 the date that you want to compare with $date1
 * @param   int $level  
 * @param   bool $absolute  
 */

function app_date_diff( $date1, $date2, $level = 3, $absolute = false ) {

    $date1 = date_create($date1);   
    $date2 = date_create($date2);
    $diff = date_diff( $date1, $date2, $absolute );

    $d = [
        'invert' => $diff->invert
    ];  

    $diffs = [
        'y' => $diff->y, 
        'm' => $diff->m, 
        'd' => $diff->d
    ];

    $level_reached = 0;

    foreach($diffs as $k=>$v) {

        if($level_reached >= $level) {
            break;
        }

        if($v > 0) {
            $d[$k] = $v;
            $level_reached++;
        }

    }

    return  $d;

}

/**
 * 
 */

function date_timestring( $periods, $format = 'latin', $separator = ',' ) {

    $formats = [
        'latin' => [
            'y' => ['year','years'],
            'm' => ['month','months'],
            'd' => ['day','days']
        ],
        'arabic' => [
            'y' => ['سنة','سنتين','سنوات'],
            'm' => ['شهر','شهرين','شهور'],
            'd' => ['يوم','يومين','أيام']
        ]
    ];

    $formats = $formats[$format];

    $string = [];

    foreach($periods as $period=>$value) {

        if(!isset($formats[$period])) {
            continue;
        }

        $string[$period] = $value.' ';
        if($format == 'arabic') {
            if($value == 2) {
                $string[$period] = $formats[$period][1];
            }elseif($value > 2 && $value <= 10) {
                $string[$period] .= $formats[$period][2];
            }else{
                $string[$period] .= $formats[$period][0];
            }

        }elseif($format == 'latin') {
            $string[$period] .= ($value > 1) ? $formats[$period][1] : $formats[$period][0];
        }

    }

    return implode($separator, $string);


}

function timeago( $date ) {

    $today = date('Y-m-d h:i:s');

    $diff = app_date_diff($date,$today,2);

    if($diff['invert'] == 1) {
        return '';
    }

    unset($diff[0]);

    $date_timestring = date_timestring($diff,'latin');

    return 'About '.$date_timestring;

}

$date1 = date('Y-m-d');
$date2 = '2018-05-14';

$diff = timeago($date2);
echo $diff;
//If difference is greater than 7 days
7 June 2019

// if difference is greater than 24 hours and less than 7 days
1 days ago
6 days ago

1 hour ago
23 hours ago

1 minute ago
58 minutes ago

1 second ago
20 seconds ago
//return current date time
function getCurrentDateTime(){
    //date_default_timezone_set("Asia/Calcutta");
    return date("Y-m-d H:i:s");
}
function getDateString($date){
    $dateArray = date_parse_from_format('Y/m/d', $date);
    $monthName = DateTime::createFromFormat('!m', $dateArray['month'])->format('F');
    return $dateArray['day'] . " " . $monthName  . " " . $dateArray['year'];
}

function getDateTimeDifferenceString($datetime){
    $currentDateTime = new DateTime(getCurrentDateTime());
    $passedDateTime = new DateTime($datetime);
    $interval = $currentDateTime->diff($passedDateTime);
    //$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
    $day = $interval->format('%a');
    $hour = $interval->format('%h');
    $min = $interval->format('%i');
    $seconds = $interval->format('%s');

    if($day > 7)
        return getDateString($datetime);
    else if($day >= 1 && $day <= 7 ){
        if($day == 1) return $day . " day ago";
        return $day . " days ago";
    }else if($hour >= 1 && $hour <= 24){
        if($hour == 1) return $hour . " hour ago";
        return $hour . " hours ago";
    }else if($min >= 1 && $min <= 60){
        if($min == 1) return $min . " minute ago";
        return $min . " minutes ago";
    }else if($seconds >= 1 && $seconds <= 60){
        if($seconds == 1) return $seconds . " second ago";
        return $seconds . " seconds ago";
    }
}
function ago($datefrom, $dateto = -1) {
    // Defaults and assume if 0 is passed in that
    // its an error rather than the epoch

    if ($datefrom == 0) {
        return "A long time ago";
    }
    if ($dateto == -1) {
        $dateto = time();
    }

    // Make the entered date into Unix timestamp from MySQL datetime field

    $datefrom = strtotime($datefrom);

    // Calculate the difference in seconds betweeen
    // the two timestamps

    $difference = $dateto - $datefrom;

    // Based on the interval, determine the
    // number of units between the two dates
    // From this point on, you would be hard
    // pushed telling the difference between
    // this function and DateDiff. If the $datediff
    // returned is 1, be sure to return the singular
    // of the unit, e.g. 'day' rather 'days'

    switch (true) {
        // If difference is less than 60 seconds,
        // seconds is a good interval of choice
        case(strtotime('-1 min', $dateto) < $datefrom):
            $datediff = $difference;
            $res = ($datediff == 1) ? $datediff . ' second' : $datediff . ' seconds';
            break;
        // If difference is between 60 seconds and
        // 60 minutes, minutes is a good interval
        case(strtotime('-1 hour', $dateto) < $datefrom):
            $datediff = floor($difference / 60);
            $res = ($datediff == 1) ? $datediff . ' minute' : $datediff . ' minutes';
            break;
        // If difference is between 1 hour and 24 hours
        // hours is a good interval
        case(strtotime('-1 day', $dateto) < $datefrom):
            $datediff = floor($difference / 60 / 60);
            $res = ($datediff == 1) ? $datediff . ' hour' : $datediff . ' hours';
            break;
        // If difference is between 1 day and 7 days
        // days is a good interval                
        case(strtotime('-1 week', $dateto) < $datefrom):
            $day_difference = 1;
            while (strtotime('-' . $day_difference . ' day', $dateto) >= $datefrom) {
                $day_difference++;
            }

            $datediff = $day_difference;
            $res = ($datediff == 1) ? 'yesterday' : $datediff . ' days';
            break;
        // If difference is between 1 week and 30 days
        // weeks is a good interval            
        case(strtotime('-1 month', $dateto) < $datefrom):
            $week_difference = 1;
            while (strtotime('-' . $week_difference . ' week', $dateto) >= $datefrom) {
                $week_difference++;
            }

            $datediff = $week_difference;
            $res = ($datediff == 1) ? 'last week' : $datediff . ' weeks';
            break;
        // If difference is between 30 days and 365 days
        // months is a good interval, again, the same thing
        // applies, if the 29th February happens to exist
        // between your 2 dates, the function will return
        // the 'incorrect' value for a day
        case(strtotime('-1 year', $dateto) < $datefrom):
            $months_difference = 1;
            while (strtotime('-' . $months_difference . ' month', $dateto) >= $datefrom) {
                $months_difference++;
            }

            $datediff = $months_difference;
            $res = ($datediff == 1) ? $datediff . ' month' : $datediff . ' months';

            break;
        // If difference is greater than or equal to 365
        // days, return year. This will be incorrect if
        // for example, you call the function on the 28th April
        // 2008 passing in 29th April 2007. It will return
        // 1 year ago when in actual fact (yawn!) not quite
        // a year has gone by
        case(strtotime('-1 year', $dateto) >= $datefrom):
            $year_difference = 1;
            while (strtotime('-' . $year_difference . ' year', $dateto) >= $datefrom) {
                $year_difference++;
            }

            $datediff = $year_difference;
            $res = ($datediff == 1) ? $datediff . ' year' : $datediff . ' years';
            break;
    }
    return $res;
}