• 10
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

How do I find the hour difference between two dates in PHP?

I have two dates, formated like "Y-m-d H:i:s". I need to compare these two dates and figure out the hour difference.

You can convert them to timestamps and go from there:

$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);

Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.

  • 67
Reply Report
      • 1
    • Using strtotime() is not the best way managing dates. Consider using DateTime::createFromFormat($date, 'Y-m-d H:i:s')->diff($dto2) or similar functionality to work with dates (+ we know the format we expect to parse). It's almost 2015 outside, lets do thing the elegant way!
    • except that createFromFormat takes $format as the first parameter ;) DateTime::createFromFormat('Y-m-d H:i:s', $date)->diff( $dto2 )

As an addition to accepted answer I would like to remind that \DateTime::diff is available!

$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);

/**
 * @var \DateInterval $diff
 */
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise

\DateInterval documentation.

  • 4
Reply Report

The problem is that using these values the result is 167 and it should be 168:

$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 /  60;
  • 1
Reply Report

This is because of day time saving. Daylight Saving Time (United States) 2014 began at 2:00 AM on Sunday, March 9.

You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to $date2 = "2014-03-14 05:49:23";

  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions