在PHP中将时间戳转换为时间戳
我有一个时间戳php代码,它没有显示正确的时间。它总是显示8小时前,而时间应该是几分钟前 /** *将timestap转换为timeago格式 *@param时间 *@返回时间 */ 公共静态函数timeago$time,$tense=ago{ ifempty$时间返回不适用; $time=strottime$time; $periods=数组秒、分钟、小时、天、周、月、年、十年; $length=array60,60,24,7,4.35,12,10; $now=时间; $difference=$now-$time; 对于$j=0;$difference>=$length[$j]&&$j在PHP中将时间戳转换为时间戳,php,timestamp,Php,Timestamp,我有一个时间戳php代码,它没有显示正确的时间。它总是显示8小时前,而时间应该是几分钟前 /** *将timestap转换为timeago格式 *@param时间 *@返回时间 */ 公共静态函数timeago$time,$tense=ago{ ifempty$时间返回不适用; $time=strottime$time; $periods=数组秒、分钟、小时、天、周、月、年、十年; $length=array60,60,24,7,4.35,12,10; $now=时间; $differen
date_default_timezone_set ( string $timezone_identifier )
这是我为你写的一个函数 它使用,所以PHP版本必须>=5.3.0 阅读函数中的注释以了解其工作原理
function timeago($time, $tense='ago') {
// declaring periods as static function var for future use
static $periods = array('year', 'month', 'day', 'hour', 'minute', 'second');
// checking time format
if(!(strtotime($time)>0)) {
return trigger_error("Wrong time format: '$time'", E_USER_ERROR);
}
// getting diff between now and time
$now = new DateTime('now');
$time = new DateTime($time);
$diff = $now->diff($time)->format('%y %m %d %h %i %s');
// combining diff with periods
$diff = explode(' ', $diff);
$diff = array_combine($periods, $diff);
// filtering zero periods from diff
$diff = array_filter($diff);
// getting first period and value
$period = key($diff);
$value = current($diff);
// if input time was equal now, value will be 0, so checking it
if(!$value) {
$period = 'seconds';
$value = 0;
} else {
// converting days to weeks
if($period=='day' && $value>=7) {
$period = 'week';
$value = floor($value/7);
}
// adding 's' to period for human readability
if($value>1) {
$period .= 's';
}
}
// returning timeago
return "$value $period $tense";
}
别忘了设定你工作的时区
date_default_timezone_set('UTC');
使用它
echo timeago('1981-06-07'); // 34 years ago
echo timeago(date('Y-m-d H:i:s')); // 0 seconds ago
等等。你期望的输入和输出是什么?使用碳依赖,它会让你更容易这是时区'timezone=>date\u default\u timezone\u get,'@DarkSterix我不确定我是否理解你的意思。您编写的是获取时区的函数。我写的是设置时区的。如果您得到的时区返回值为false,那么您将得到与您的时区不同的时区的时间。由于函数返回的时区正确,我不明白为什么它从8小时前开始,而不是从1或2小时前开始,或者minutes@DarkSterix在您的问题中添加您也调用函数和all的部分。`'
function time_elapsed($datetime, $full = false) {
$now = time();
$ago = strtotime($datetime);
$diff = $now - $ago;
$string = array(
'year' => 31104000,
'month' => 2592000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute'=> 60,
'second'=> 1
);
$data = array();
foreach ($string as $k => $v) {
if($diff > $v){
$count = round($diff / $v);
$data[$k] = $count . (($count > 1) ? ' ' . $k .'s' : ' ' . $k);
$diff = $diff % $v;
}
}
if (!$full) $data = array_slice($data, 0, 1);
return $data ? implode(', ', $data) . ' ago' : 'just now';
}
echo time_elapsed('2016-01-18 13:07:30', true);
// 2 years, 1 month, 2 weeks, 6 days, 25 seconds ago
echo time_elapsed('2016-01-18 13:07:30');
// 2 years ago