【问题标题】:Interval between dates including hours php日期之间的间隔,包括小时 php
【发布时间】:2015-11-21 03:53:29
【问题描述】:

我想查找日期之间的间隔,小时功能在时间更改前一小时无法正常工作。我知道有一个答案可以部分回答这个问题here。但它不按小时回答。

我有以下 php 代码:

//helper function to pluralize words
function pluralize( $count, $text ){ 
    return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}

/**
 * Difference of dates
 * @param type $date1 DateTime first date
 * @param type $date2 DateTime second date
 * @return type string year, month, day, hour, minute, second 
 */
function timeDiff($date1, $date2 ){
    $string = "";  
    $interval =$date1->diff($date2);
    $suffix = ( $interval->invert ? ' ago' : '' );
    if ( $v = $interval->y >= 1 ) $string .= pluralize( $interval->y, 'year' ). ', ';
    if ( $v = $interval->m >= 1 ) $string .= pluralize( $interval->m, 'month' ). ', ';
    if ( $v = $interval->d >= 1 ) $string .= pluralize( $interval->d, 'day' ). ', ';
    if ( $v = $interval->h >= 1 ) $string .= pluralize( ($interval->h), 'hour' ) . ', ';
    if ( $v = $interval->i >= 1 ) $string .= pluralize( $interval->i, 'minute' ). ', ';
    if ( $v = $interval->i >= 1 ) $string .= pluralize( $interval->s, 'second' ). ' ';
    return $string . $suffix;
}

我希望通过以下测试。

$date1 = new DateTime("2014-05-10 20:00:00");
$date2 = new DateTime("2015-11-20 19:45:00");

//This should produce "1 year, 6 months, 9 days, 23 hours, 45 minutes"
//But it does produce "1 year, 6 months, 10 days, 45 minutes"
timeDiff($date1, $date2); 

$date3 = new DateTime("2015-11-20 20:00:00");

//This should, and does produce "1 year, 6 months, 10 days"
timeDiff($date1, $date3); 

这看起来像 @John Conde 在 cmets 中指出的 version issue。它已在 PHP 5.4.24 及更高版本的新版本中修复。对于以前版本的 PHP,我该如何解决这个问题?

【问题讨论】:

标签: php datetime intervals


【解决方案1】:

我猜您的要求是显示本地时间表示的两个 DateTime 数据项之间的经过时间。 (如果这不是您的要求,请更新您的问题)。

我还猜想您的 DateTime 项目是在当地时区正确创建的。例如,您可以使用date_default_timezone_get() 检查本地时区设置,并使用date_default_timezone_set('Australia/Sydney') 进行设置。

可能是您服务器的操作者错误地设置了服务器默认时区,或者它位于您以外的某个时区。也有可能将其设置为 UTC(也称为 Zulu 或 Z 时间,以前称为格林威治标准时间或 GMT)。在这种情况下,您需要在程序中明确设置本地时区。

正确设置时区后,创建 DateTime 项。然后将两个 DateTime 项都转换为 UTC。然后计算差异。这样的事情应该可以解决问题。

 $utczone = new DateTimeZone('UTC');
 timeDiff($date1->setTimezone($utczone), $date2->setTimezone($utczone));

【讨论】:

  • 是PHP的版本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多