【问题标题】:PHP datetime diff wrongPHP日期时间差异错误
【发布时间】:2016-06-15 13:23:33
【问题描述】:

我试图区分 PHP 中的两个 DateTime 对象,但答案似乎是错误的。如您所见,diff() 函数给出了 4 小时 41 分钟的时差,但显然时差更接近 7 小时。

$eastern_tz = new DateTimeZone( "US/Eastern" );

$now         = new DateTime( "now", $eastern_tz );
$future_date = new DateTime( $future_date_string ); //'2011-05-11 12:00:00'

$future_date->setTimezone( $eastern_tz );

$interval = $future_date->diff( $now );

var_dump( $now );
var_dump( $future_date );
var_dump( $interval );

return $interval->format( $format ); //"%d days, %h hours, %i minutes, %s seconds"

//调试信息

object(DateTime)[483]
  public 'date' => string '2016-06-15 09:18:41' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'US/Eastern' (length=10)
object(DateTime)[484]
  public 'date' => string '2016-06-15 14:00:00' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'US/Eastern' (length=10)
object(DateInterval)[479]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 0
  public 'h' => int 4
  public 'i' => int 41
  public 's' => int 19
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 1
  public 'days' => int 0
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

【问题讨论】:

  • 好吧,您的调试信息显示 $future_date 值不是您声称要插入的值。你确定你在 $future_date_string 中提供的值是正确的吗?
  • 根据调试信息中显示的值,答案是正确的!

标签: php datetime dateinterval


【解决方案1】:

当您创建$future_date = new DateTime( $future_date_string ); 时,PHP 的默认时区是哪个?

$future_date->setTimezone( $eastern_tz ); 仅在渲染日期或导入新字符串时才需要。解析$future_date_string 为时已晚。

【讨论】:

    【解决方案2】:

    使用我的代码,它会为你工作。

    $fromTimes = date('d-m-Y',strtotime('15-06-2016 06:57:27')); //from date and time
    $toTimess = date('d-m-Y',strtotime('17-06-2016 10:25:30')); //to date and time
    $date_a = new DateTime($toTimess); //converting the date and time
    $date_b = new DateTime($fromTimes);
    $interval = date_diff($date_a,$date_b); //find difference 
    $day = $interval->format('%d')*24; //get day difference
    $hours = $interval->format('%h'); // get hour
    $mins = $interval->format('%i'); //get mins
    if($mins <10)
    { $mins = '0'.$mins; }
    echo $total_hours = ($hours + $day).':'.$mins;
    

    希望它对你有用...

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多