dongtaihui5131 2012-06-22 16:20
浏览 56
已采纳

PHP计算分钟差异

I am working out the months, days, hours and minutes between two dates, I have successfully got it to work out the months, days and minutes, but I cannot for the life of get it to work out the minutes, below is my code.

<?php
    $date1 = "2012-07-01 00:00:00";
    $date2 = "2012-09-30 00:00:00";

    $diff = abs(strtotime($date2) - strtotime($date1));

    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
    $minutes = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24) / (60*60*24) / (60*60));

    printf("%d years, %d months, %d days, %d minutes
", $years, $months, $days, $minutes);

?>
  • 写回答

3条回答 默认 最新

  • dongwu1410 2012-06-22 16:29
    关注

    The best and most accurate way to approach this problem is to use the DateTime class. Otherwise you'll run into issues when you deal with anomalies in dates (leap year, etc).

    $format = 'Y-m-d h:i:s';
    $tz = new DateTimeZone('America/New_York');
    
    // Create DateTime objs based on the above format
    $t1 = DateTime::createFromFormat( $format, "2012-07-01 00:00:00", $tz);
    $t2 = DateTime::createFromFormat( $format, "2012-09-30 00:00:00", $tz);
    
    // Find the difference between them
    $diff = $t1->diff( $t2);
    
    // Print out the difference in each amount
    $outputs = array( 'Y' => 'Year', 'm' => 'Month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'seconds');
    
    foreach( $outputs as $key => $value)
        echo $diff->format( '%'.$key) . ' ' . $value . "
    ";
    

    This outputs:

    00 Year
    2 Month
    29 day
    0 hour
    0 minute
    0 seconds
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接