How can i calculate hours between two dates in php?

How do I calculate the difference between two dates in hours?

For example:

day1=2006-04-12 12:30:00
day2=2006-04-14 11:30:00

In this case the result should be 47 hours.

asked Jun 24, 2010 at 9:17

3

The newer PHP-Versions provide some new classes called DateTime, DateInterval, DateTimeZone and DatePeriod. The cool thing about this classes is, that it considers different timezones, leap years, leap seconds, summertime, etc. And on top of that it's very easy to use. Here's what you want with the help of this objects:

// Create two new DateTime-objects...
$date1 = new DateTime['2006-04-12T12:30:00'];
$date2 = new DateTime['2006-04-14T11:30:00'];

// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff[$date1];

// Call the format method on the DateInterval-object
echo $diff->format['%a Day and %h hours'];

The DateInterval-object, which is returned also provides other methods than format. If you want the result in hours only, you could to something like this:

$date1 = new DateTime['2006-04-12T12:30:00'];
$date2 = new DateTime['2006-04-14T11:30:00'];

$diff = $date2->diff[$date1];

$hours = $diff->h;
$hours = $hours + [$diff->days*24];

echo $hours;

And here are the links for documentation:

  • DateTime-Class
  • DateTimeZone-Class
  • DateInterval-Class
  • DatePeriod-Class

All these classes also offer a procedural/functional way to operate with dates. Therefore take a look at the overview: //php.net/manual/book.datetime.php

Glavić

41.6k13 gold badges74 silver badges107 bronze badges

answered Jun 24, 2010 at 9:47

FidiFidi

5,5541 gold badge17 silver badges25 bronze badges

7

$t1 = strtotime[ '2006-04-14 11:30:00' ];
$t2 = strtotime[ '2006-04-12 12:30:00' ];
$diff = $t1 - $t2;
$hours = $diff / [ 60 * 60 ];

answered Jun 24, 2010 at 9:20

Jan HančičJan Hančič

52.3k16 gold badges94 silver badges99 bronze badges

3

To provide another method for DatePeriod when using the UTC or GMT timezone.

Count Hours //3v4l.org/Mu3HD

$start = new \DateTime['2006-04-12T12:30:00'];
$end = new \DateTime['2006-04-14T11:30:00'];

//determine what interval should be used - can change to weeks, months, etc
$interval = new \DateInterval['PT1H'];

//create periods every hour between the two dates
$periods = new \DatePeriod[$start, $interval, $end];

//count the number of objects within the periods
$hours = iterator_count[$periods];
echo $hours . ' hours'; 

//difference between Unix Epoch
$diff = $end->getTimestamp[] - $start->getTimestamp[];
$hours = $diff / [ 60 * 60 ];
echo $hours . ' hours [60 * 60]';

//difference between days
$diff = $end->diff[$start];
$hours = $diff->h + [$diff->days * 24];
echo $hours . ' hours [days * 24]';

Result

47 hours [iterator_count]
47 hours [60 * 60]
47 hours [days * 24]

Count Hours with Daylight Savings //3v4l.org/QBQUB

Please be advised that DatePeriod excludes an hour for DST but does not add another hour when DST ends. So its usage is subjective to your desired outcome and date range.

See the current bug report

//set timezone to UTC to disregard daylight savings
date_default_timezone_set['America/New_York'];

$interval = new \DateInterval['PT1H'];

//DST starts Apr. 2nd 02:00 and moves to 03:00
$start = new \DateTime['2006-04-01T12:00:00'];  
$end = new \DateTime['2006-04-02T12:00:00'];

$periods = new \DatePeriod[$start, $interval, $end];
$hours = iterator_count[$periods];
echo $hours . ' hours';

//DST ends Oct. 29th 02:00 and moves to 01:00
$start = new \DateTime['2006-10-28T12:00:00'];
$end = new \DateTime['2006-10-29T12:00:00']; 

$periods = new \DatePeriod[$start, $interval, $end];
$hours = iterator_count[$periods];
echo $hours . ' hours';

Result

#2006-04-01 12:00 EST to 2006-04-02 12:00 EDT
23 hours [iterator_count]
//23 hours [60 * 60]
//24 hours [days * 24]

#2006-10-28 12:00 EDT to 2006-10-29 12:00 EST
24 hours [iterator_count]
//25 hours [60 * 60]
//24 hours [days * 24]

#2006-01-01 12:00 EST to 2007-01-01 12:00 EST
8759 hours [iterator_count]
//8760 hours [60 * 60]
//8760 hours [days * 24]

//------

#2006-04-01 12:00 UTC to 2006-04-02 12:00 UTC
24 hours [iterator_count]
//24 hours [60 * 60]
//24 hours [days * 24]

#2006-10-28 12:00 UTC to 2006-10-29 12:00 UTC
24 hours [iterator_count]
//24 hours [60 * 60]
//24 hours [days * 24]

#2006-01-01 12:00 UTC to 2007-01-01 12:00 UTC
8760 hours [iterator_count]
//8760 hours [60 * 60]
//8760 hours [days * 24]

answered Mar 4, 2016 at 16:57

Will B.Will B.

16.3k4 gold badges61 silver badges67 bronze badges

6

your answer is:

round[[strtotime[$day2] - strtotime[$day1]]/[60*60]]

answered Jun 24, 2010 at 9:20

Sergey EreminSergey Eremin

10.8k2 gold badges37 silver badges44 bronze badges

1

The easiest way to get the correct number of hours between two dates [datetimes], even across daylight saving time changes, is to use the difference in Unix timestamps. Unix timestamps are seconds elapsed since 1970-01-01T00:00:00 UTC, ignoring leap seconds [this is OK because you probably don't need this precision, and because it's quite difficult to take leap seconds into account].

The most flexible way to convert a datetime string with optional timezone information into a Unix timestamp is to construct a DateTime object [optionally with a DateTimeZone as a second argument in the constructor], and then call its getTimestamp method.

$str1 = '2006-04-12 12:30:00'; 
$str2 = '2006-04-14 11:30:00';
$tz1 = new DateTimeZone['Pacific/Apia'];
$tz2 = $tz1;
$d1 = new DateTime[$str1, $tz1]; // tz is optional,
$d2 = new DateTime[$str2, $tz2]; // and ignored if str contains tz offset
$delta_h = [$d2->getTimestamp[] - $d1->getTimestamp[]] / 3600;
if [$rounded_result] {
   $delta_h = round [$delta_h];
} else if [$truncated_result] {
   $delta_h = intval[$delta_h];
}
echo "Δh: $delta_h\n";

answered Jan 29, 2014 at 21:30

Walter TrossWalter Tross

11.9k2 gold badges38 silver badges61 bronze badges

3

//Calculate number of hours between pass and now
$dayinpass = "2013-06-23 05:09:12";
$today = time[];
$dayinpass= strtotime[$dayinpass];
echo round[abs[$today-$dayinpass]/60/60];

answered Apr 11, 2014 at 5:51


answered Jan 26, 2014 at 0:31

1

$day1 = "2006-04-12 12:30:00"
$day1 = strtotime[$day1];
$day2 = "2006-04-14 11:30:00"
$day2 = strtotime[$day2];

$diffHours = round[[$day2 - $day1] / 3600];

I guess strtotime[] function accept this date format.

answered Jun 24, 2010 at 9:21

Boris DelormasBoris Delormas

2,4891 gold badge19 silver badges27 bronze badges

Unfortunately the solution provided by FaileN doesn't work as stated by Walter Tross.. days may not be 24 hours!

I like to use the PHP Objects where possible and for a bit more flexibility I have come up with the following function:

/**
 * @param DateTimeInterface $a
 * @param DateTimeInterface $b
 * @param bool              $absolute Should the interval be forced to be positive?
 * @param string            $cap The greatest time unit to allow
 *
 * @return DateInterval The difference as a time only interval
 */
function time_diff[DateTimeInterface $a, DateTimeInterface $b, $absolute=false, $cap='H']{

  // Get unix timestamps, note getTimeStamp[] is limited
  $b_raw = intval[$b->format["U"]];
  $a_raw = intval[$a->format["U"]];

  // Initial Interval properties
  $h = 0;
  $m = 0;
  $invert = 0;

  // Is interval negative?
  if[!$absolute && $b_rawinvert=$invert;

  return $interval;
}

This like date_diff[] creates a DateTimeInterval, but with the highest unit as hours rather than years.. it can be formatted as usual.

$interval = time_diff[$date_a, $date_b];
echo $interval->format['%r%H']; // For hours [with sign]

N.B. I have used format['U'] instead of getTimestamp[] because of the comment in the manual. Also note that 64-bit is required for post-epoch and pre-negative-epoch dates!

answered May 6, 2015 at 14:07

ArthArth

12.3k5 gold badges35 silver badges68 bronze badges

0

Carbon could also be a nice way to go.

From their website:

A simple PHP API extension for DateTime. //carbon.nesbot.com/

Example:

use Carbon\Carbon;

//...

$day1 = Carbon::createFromFormat['Y-m-d H:i:s', '2006-04-12 12:30:00'];
$day2 = Carbon::createFromFormat['Y-m-d H:i:s', '2006-04-14 11:30:00'];

echo $day1->diffInHours[$day2]; // 47

//...

Carbon extends the DateTime class to inherit methods including diff[]. It adds nice sugars like diffInHours, diffInMintutes, diffInSeconds e.t.c.

answered Apr 19, 2018 at 6:17

joshuamabinajoshuamabina

1,34017 silver badges25 bronze badges

This function helps you to calculate exact years and months between two given dates, $doj1 and $doj. It returns example 4.3 means 4 years and 3 month.


geomagas

3,2101 gold badge16 silver badges27 bronze badges

answered Jun 24, 2010 at 15:08

1

To pass a unix timestamp use this notation

$now        = time[];
$now        = new DateTime["@$now"];

answered Dec 11, 2016 at 16:06

1

First, you should create an interval object from a range of dates. By the wording used in this sentence alone, one can easily identify basic abstractions needed. There is an interval as a concept, and a couple of more ways to implement it, include the one already mentioned -- from a range of dates. Thus, an interval looks like that:

$interval =
    new FromRange[
        new FromISO8601['2017-02-14T14:27:39+00:00'],
        new FromISO8601['2017-03-14T14:27:39+00:00']
    ];

FromISO8601 has the same semantics: it's a datetime object created from iso8601-formatted string, hence the name.

When you have an interval, you can format it however you like. If you need a number of full hours, you can have

[new TotalFullHours[$interval]]->value[];

If you want a ceiled total hours, here you go:

[new TotalCeiledHours[$interval]]->value[];

For more about this approach and some examples, check out this entry.

answered May 9, 2020 at 13:59

Vadim SamokhinVadim Samokhin

3,3044 gold badges39 silver badges66 bronze badges

In addition to @fyrye's very helpful answer this is an okayish workaround for the mentioned bug [this one], that DatePeriod substracts one hour when entering summertime, but doesn't add one hour when leaving summertime [and thus Europe/Berlin's March has its correct 743 hours but October has 744 instead of 745 hours]:

Counting the hours of a month [or any timespan], considering DST-transitions in both directions

function getMonthHours[string $year, string $month, \DateTimeZone $timezone]: int
{
    // or whatever start and end \DateTimeInterface objects you like
    $start = new \DateTimeImmutable[$year . '-' . $month . '-01 00:00:00', $timezone];
    $end = new \DateTimeImmutable[[new \DateTimeImmutable[$year . '-' . $month . '-01 23:59:59', $timezone]]->format['Y-m-t H:i:s'], $timezone];
    
    // count the hours just utilizing \DatePeriod, \DateInterval and iterator_count, hell yeah!
    $hours = iterator_count[new \DatePeriod[$start, new \DateInterval['PT1H'], $end]];
    
    // find transitions and check, if there is one that leads to a positive offset
    // that isn't added by \DatePeriod
    // this is the workaround for //bugs.php.net/bug.php?id=75685
    $transitions = $timezone->getTransitions[[int]$start->format['U'], [int]$end->format['U']];
    if [2 === count[$transitions] && $transitions[0]['offset'] - $transitions[1]['offset'] > 0] {
        $hours += [round[[$transitions[0]['offset'] - $transitions[1]['offset']]/3600]];
    }
    
    return $hours;
}

$myTimezoneWithDST = new \DateTimeZone['Europe/Berlin'];
var_dump[getMonthHours['2020', '01', $myTimezoneWithDST]]; // 744
var_dump[getMonthHours['2020', '03', $myTimezoneWithDST]]; // 743
var_dump[getMonthHours['2020', '10', $myTimezoneWithDST]]; // 745, finally!

$myTimezoneWithoutDST = new \DateTimeZone['UTC'];
var_dump[getMonthHours['2020', '01', $myTimezoneWithoutDST]]; // 744
var_dump[getMonthHours['2020', '03', $myTimezoneWithoutDST]]; // 744
var_dump[getMonthHours['2020', '10', $myTimezoneWithoutDST]]; // 744

P.S. If you check a [longer] timespan, which leads to more than those two transitions, my workaround won't touch the counted hours to reduce the potential of funny side effects. In such cases, a more complicated solution must be implemented. One could iterate over all found transitions and compare the current with the last and check if it is one with DST true->false.

answered Jul 29, 2020 at 10:30

spackmatspackmat

8529 silver badges23 bronze badges

$diff_min = [ strtotime[ $day2 ] - strtotime[ $day1 ] ] / 60 / 60;
$total_time  = $diff_min;

You can try this one.

fcdt

2,2615 gold badges12 silver badges26 bronze badges

answered Aug 15, 2020 at 18:30

0

This is working in my project. I think, This will be helpful for you.

If Date is in past then invert will 1.
If Date is in future then invert will 0.

$defaultDate = date['Y-m-d'];   
$datetime1   = new DateTime['2013-03-10'];  
$datetime2   = new DateTime[$defaultDate];  
$interval    = $datetime1->diff[$datetime2];  
$days        = $interval->format['%a'];
$invert      = $interval->invert;

answered Nov 16, 2016 at 5:49

Gurudutt SharmaGurudutt Sharma

4842 gold badges6 silver badges18 bronze badges

How can I calculate the number of hours between two dates in PHP?

Show activity on this post. $day1 = "2006-04-12 12:30:00" $day1 = strtotime[$day1]; $day2 = "2006-04-14 11:30:00" $day2 = strtotime[$day2]; $diffHours = round[[$day2 - $day1] / 3600];

How do I calculate total hours in PHP?

There are two ways to calculate the total time from the array. Using strtotime[] function: The strtotime[] function is used to convert string into the time format. This functions returns the time in h:m:s format.

How can I get days between two dates in PHP?

The date_diff[] function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.

How can I get hours and minutes in PHP?

Try this: $hourMin = date['H:i']; This will be 24-hour time with an hour that is always two digits. For all options, see the PHP docs for date[].

Chủ Đề