我正在尝试转换格式为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?)格式?
我修改了原来的函数一点(在我看来更有用,或更符合逻辑)。
// 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;
}
举个例子:
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);
输入可以是任何受支持的日期和时间格式。
输出:
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';
}
这是我的解决方案,请检查并根据您的要求修改
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需要做一些工作。我欢迎就如何改进提出意见。电话为:
Echo time_elapsed_string('2014-11-14 09: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;
}
我发现结果如下:
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',
);
一些语言显示时间之前有一些问题,例如阿拉伯语,有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天
我想有一个荷兰版本,支持单复数。仅仅在结尾加一个“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';
}
你应该先测试一下,因为我不是一个优秀的程序员:)