这里我正在做剩余的城镇时间,比如假设事件要开始2018-04-18 04:30 PM
,假设当前时间是2018-04-18 04:10 PM
意味着我想显示剩下的20分钟,我看到代码但它是显示错误的结果
我的PHP代码:
<?php
date_default_timezone_set('UTC');
date_default_timezone_set('Asia/Kolkata');
function timeAgo($logintime)
{
$start_date = new DateTime($logintime);
$since_start = $start_date->diff(new DateTime(date("Y-m-d h:i:s")));//2018-04-18 04:10 PM
if( intval($since_start->format('%Y') ) >= 1){
$timeago = $since_start->format('%Y years');
}
else if(intval($since_start->format('%m')) >= 1){
$timeago = $since_start->format('%m months ');
}
else if(intval($since_start->format('%a')) >= 1){
$timeago = $since_start->format('%a days ');
}
else if(intval($since_start->format('%h')) >= 1){
$timeago = $since_start->format('%h hours ');
}
else if(intval($since_start->format('%i')) >= 1){
$timeago = $since_start->format('%i minutes ');
}
else if(intval($since_start->format('%s')) >= 1){
$timeago = $since_start->format('%s seconds ');
}
return $timeago;
}
echo timeAgo('2018-04-18 04:30 PM');
?>
我得到这样的结果
12小时
我的预期输出是
剩下20分钟
答案 0 :(得分:-1)
您只需提供现在的DateTime。您不想声明时间格式。而您只需使用此时区date_default_timezone_set('Asia/Kolkata');
。这是代码:
date_default_timezone_set('Asia/Kolkata');
function timeAgo($logintime)
{
$start_date = new DateTime($logintime);
$since_start = new DateTime();
$interval = $since_start->diff($start_date);
$timeago = $interval->format("%a days, %h hours, %i minutes, %s seconds");
if($since_start < $start_date){
return $timeago. ' ago';
}else{
return 'This Event Passed';
}
}
echo timeAgo('2018-04-19 05:50 PM');
Out put:
1天,0小时,56分钟,28秒前