【问题标题】:Getting the difference between two time/dates using php?使用 php 获取两个时间/日期之间的差异?
【发布时间】:2010-12-18 17:44:44
【问题描述】:

我想使用 php 找出格式为 d-m-Y H:i (14-04-2009 12:15) 的两个日期之间的分钟时差?

【问题讨论】:

    标签: php


    【解决方案1】:

    使用 strtotime() 将时间解析为时间戳,然后简单地从另一个中减去一个。

    之后,您可以使用数学函数获取分钟数、天数等​​。

    例如:

    // $date1 and $date2 are given
    // the difference is in seconds
    $difference = strtotime($date1) - strtotime($date2);
    
    // getting the difference in minutes
    $difference_in_minutes = $difference / 60;
    

    参考:strtotime()

    【讨论】:

    • 当月份和日期的数字使格式不明确时,PHP 可能会假设您的日期是 m-d-Y 格式(您给出的示例是明确的,因为没有 14 个月)。您可能需要解析和交换日期和月份。
    • 当然,我没有意识到给定的日期不是标准的美英格式。
    • 没错。 strtotime 可能会给您带来意想不到的结果,因为您使用的日期格式不寻常。
    • strtotime() 在分隔符为连字符时采用欧洲/澳大利亚格式 (dd-mm-yyyy)。正斜杠使其使用美国格式 (mm-dd-yyyy)
    【解决方案2】:
    date_default_timezone_set('Asia/Kolkata');
    $currentDateTime = date('m/d/Y H:i:s');
    $model_current_time = date('Y-m-d H:i:s', 
    strtotime($currentDateTime));
    echo $model_current_time."------";
    
    $date = DateTime::createFromFormat('d/m/Y h:i:s A', 
    $row['model_creation_time']);//get from resouses
    $new_date_format = $date->format('m/d/Y H:i:s');
    $model_creation_time = date('Y-m-d H:i:s', 
    strtotime($new_date_format));
    echo $model_creation_time;
    
    $datetime1 = new DateTime($model_current_time);
    $datetime2 = new DateTime($model_creation_time);
    $interval = $datetime1->diff($datetime2);
    echo $interval->d;
    echo $interval->h;
    echo $interval->s;
    

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      相关资源
      最近更新 更多