dqg63264 2018-02-02 04:23
浏览 41
已采纳

日期和时间差异在PHP中无法正常工作

here i want to do employee login time calculation,like

  1. My office login time is 2018-02-01 09:30 AM
  2. But my logged in time 2018-02-01 09:40 AM

based on above two dates i came to office 10 Mins late.

suppose my logged in time 2018-02-01 10:40 AM (1 Hr and 20 mins late)

My expected results (Mins late means)

10 Mins late

My expected results (Hrs late means)

1 Hrs late

I tried like this but it is not working properly

    date_default_timezone_set('UTC');
$officeTiming ="2018-02-01 09:30 AM";
$todaymyloginTime ="2018-02-01 09:40 AM";
$datetime1 = date_create($officeTiming);
$datetime2 = date_create($todaymyloginTime);
$interval = date_diff($datetime1, $datetime2);
$suffix = ' Late'; 
    if ($datetime1 > $datetime2) $suffix = ' Before';
    $time_diff= $interval->format('%h:%i:%s'); 
    $start_date = new DateTime($time_diff);
    $since_start = $start_date->diff(new DateTime(date("h:i:s")));
    if(intval($since_start->format('%h')) >= 1){
         $timeago = $since_start->format('%h hours'.$suffix);    
    }
    else if(intval($since_start->format('%i')) >= 1){
         $timeago = $since_start->format('%i minutes'.$suffix);  
    }
    else if(intval($since_start->format('%s')) >= 1){
         $timeago = $since_start->format('%s seconds'.$suffix); 
    }
    echo $timeago; 

I am getting answer is 4 hours Late but actually i am 20 mins late

My working code

$datetime1 = new DateTime('2018-02-01 09:30 AM');
 $datetime2 = new DateTime('2018-02-01 09:20 AM');
 $interval = $datetime1->diff($datetime2);
 $suffix = ' Late'; 
if ($datetime1 > $datetime2) $suffix = ' Before';

 if($interval->format('%h') ==0){
     echo $interval->format('%i')." Minutes".$suffix;
 }else{
    echo $interval->format('%h')." Hours".$suffix; 
  }
  • 写回答

2条回答 默认 最新

  • dongluojiao6322 2018-02-02 04:27
    关注

    May be You are looking for this kind of stuff:-

    <?php
    $datetime1 = new DateTime('2018-02-01 09:30:31 AM');
    $datetime2 = new DateTime('2018-02-01 09:40:32 AM');
    $interval = $datetime1->diff($datetime2);
    if($interval->format('%h') ==0){
        echo $interval->format('%i')." Minutes".$interval->format('%s')." Seconds Late";
    }else{
        echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes ".$interval->format('%s')." Seconds Late"; 
    }
    ?>
    

    Output:-

    10 Minutes 1 Seconds Late
    

    Hope it helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化