Basic PHP Time calculation having a wrong answer - php

I have this basic PHP time calculation which just substracts between two timestamps but it's giving back an additional hour.
echo date('h:i:s',strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00'));
I am expecting the answer to be 55 min ( 00:55:00 )
Instead it gives 01:55:00
EDIT: On PHP fiddle it works fine, on my server it doesn't (and the time is set properly)
Any insight?

create date object by date_create() function
$date1 = date_create("y-m-d H:i:s");
$date2 = date_create("y-m-d H:i:s");
print_r(date_diff($date1-$date2));
you can get the diff of year, month , hour , min, sec

Try this. See comments for explanation and output.
<?php
$from = '2020-11-15 11:05:00';
$to = '2020-11-15 12:00:00';
// 'U' gets UNIX seconds since epoch.
$fromSeconds = (new DateTime($from))->format('U');
$toSeconds = (new DateTime($to))->format('U');
$interval = $toSeconds - $fromSeconds;
// Get number of days
$days = floor($interval / 86400);
$interval -= $days * 86400;
// Get number of hours
$hours = floor($interval / 3600);
$interval -= $hours * 3600;
// Get number of minutes
$minutes = floor($interval / 60);
$interval -= $hours * 60;
var_dump($days); // 0
var_dump($hours); // 0
var_dump($minutes); // 55
This explains what happened in your first attempt:
$seconds = strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00');
var_dump($seconds); // 3300
// You're passing an _interval_ to date(), where it expects a timestamp
// in UNIX epoch format.
// Which means, seconds counted from UNIX time 0.
// UNIX time 0 starts at 1970-01-01 01:00:00!
// See:
echo date('Y-m-d H:i:s', 0); // 1970-01-01 01:00:00!
// Your code is formatting the TIME, not the INTERVAL of your argument.
// Which is the 1 from 01:00:00 and 55 minutes from your value.

Related

Carbon show time different days hours minutes second

i try to make time difference with carbon
$dt = Carbon::parse('2018-07-15 00:00:00');
$now = Carbon::now('Asia/Dubai'); //set current time
$seconds = $now->diffInSeconds( $dt ); //difference turn into second
$days = $dt->diffInDays($dt->copy()->addSeconds($seconds));
$hours = $dt->diffInHours($dt->copy()->addSeconds($seconds)->subDays($days));
$minutes = $dt->diffInMinutes($dt->copy()->addSeconds($seconds)->subHours($hours));
$days result are 12 (its right).
$hours result are 8 (seems not right).
$minutes result are 17299 (clearly wrong).
how to get the result for example 12 day 5 hours 45 minutes
Actually functions like diffInSeconds give total difference in seconds that's why the number is so large,to get the minutes for the time difference right you can use -:
$minutes = ($now->minute - $dt->minute);

PHP Calculate Exact number of hours minutes and seconds between two timestamps

I have two Timestamps
2016-01-01 00:00:00
2016-01-02 23:59:59
Using PHP how can I calculate the number of hours and minutes between the two times and get the result as a decimal with 2 places after the .
currently I have this:
$Start = new DateTime($StartTime);
$Finish = new DateTime ($FinishTime);
$Interval = date_diff($Start,$Finish);
$Hours = $Interval->format('%h.%i');
But the result is incorrect if the user starts the timer on Day 1 and finishes on day 2.
You could multiply the number of days by 24 to convert them to hours, then sum the hours and concatenate the minutes:
$start = new DateTime('2016-01-01 00:00:00');
$end = new DateTime('2016-01-02 23:59:59');
$interval = $end->diff($start);
$days = $interval->format('%d');
$hours = 24 * $days + $interval->format('%h');
echo $hours.':'.$interval->format('%i');
You could format the DateTime as a UNIX timestamp, and then simply subtract to get the total seconds, and format the output with gmdate().
$Start = new DateTime($StartTime);
$Finish = new DateTime ($FinishTime);
$Interval = $Start->format('U') - $Finish->format('U');
$Hours = gmdate("H:i:s", $Interval);
Try this.
$Hours = $Interval->format('%a.%h.%i');

How to get the hour minute and second?

The future time is :2012-05-26 00:00:00
supposed there are three variable: $hour $minute $second
now, i want to using the future time subtract now time. then give the left hour to $hour,give the left minute to $minute,give the left second to $second.
i am sorry i am new of php, now i get stucked how to do the math operation ? thank you
A very good resource for dates and time..
http://www.php.net/manual/en/function.time.php
-there are samples here doing something similar.
Check the date_diff function. There's the exact solution to what you're asking there.
And here's the page (DateInterval::format) documenting how you can format the output.
$now = date_create();
// use "now" and necessary DateTimeZone in the arguments
$otherDate = date_create('2020-04-13');
$interval = date_diff($now, $futureDate);
echo $interval->format('%a days');
The following are the math operations for the difference in hours,minutes and seconds
$future_datetime = '2012-05-26 00:00:00';
$future = strtotime($future_datetime); //future datetime in seconds
$now_datetime = date('Y-m-d H:i:s');
$now = date('U'); //now datetime in seconds
//The math for calculating the difference in hours, minutes and seconds
$difference = $future - $now;
$second = 1;
$minute = 60 * $second;
$hour = 60 * $minute;
$difference_hours = floor($difference/$hour);
$remainder = $difference - ($difference_hours * $hour);
$difference_minutes = floor($remainder/$minute);
$remainder = $remainder - ($difference_minutes * $minute);
$difference_seconds = $remainder;
echo "The difference between $future_datetime and $now_datetime is $difference_hours hours, $difference_minutes minutes and $difference_seconds seconds";

Get duration between date time formats

how to get duration between start_date and end_date in hrs min sec format in php?
$start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29
Use DateTime class:
$start_date = new DateTime('2012-03-23 11:58:14');
$end_date = new DateTime('2012-03-24 11:54:29');
$dd = date_diff($end_date, $start_date);
To get hours use $dd->h, minutes - $dd->i, seconds - $dd->s.
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
I would
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo date('H:i:s', $difference);
EDIT
I made an error in assuming that the time difference would be less then a day, so if the time difference is greater then a day, you will only see the Hours:minuetes:seconds, which is probably not what you want (if it is ignore this)
So I would now
$seconds = $difference % 60; //seconds
$difference = floor($difference / 60);
$min = $difference % 60; // min
$difference = floor($difference / 60);
$hours = $difference; //hours
echo "$hours : $min : $seconds";
Sorry for the correction
This function will help you
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
/*
$interval can be:
yyyy - Number of full years
q - Number of full quarters
m - Number of full months
y - Difference between day numbers
(eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
d - Number of full days
w - Number of full weekdays
ww - Number of full weeks
h - Number of full hours
n - Number of full minutes
s - Number of full seconds (default)
*/
http://php.net/manual/en/function.date-diff.php
format those string to date
transform those date to milliseconds
do endate - stardate
from the result calculate the h:mm:ss
See it working here: http://codepad.viper-7.com/FPuOks
$start_date="2012-03-22 11:58:14";
$end_date="2012-03-24 11:54:29";
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo sprintf("%02d%s%02d%s%02d", floor($difference/3600), ':', ($difference/60)%60, ':', $difference%60); // outputs 47:56:15

Calculate number of hours between 2 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.
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: http://php.net/manual/book.datetime.php
$t1 = strtotime( '2006-04-14 11:30:00' );
$t2 = strtotime( '2006-04-12 12:30:00' );
$diff = $t1 - $t2;
$hours = $diff / ( 60 * 60 );
To provide another method for DatePeriod when using the UTC or GMT timezone.
Count Hours https://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 https://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)
your answer is:
round((strtotime($day2) - strtotime($day1))/(60*60))
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";
//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);
<?
$day1 = "2014-01-26 11:30:00";
$day1 = strtotime($day1);
$day2 = "2014-01-26 12:30:00";
$day2 = strtotime($day2);
$diffHours = round(($day2 - $day1) / 3600);
echo $diffHours;
?>
$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.
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_raw<$a_raw){
$invert = 1;
}
// Working diff, reduced as larger time units are calculated
$working = abs($b_raw-$a_raw);
// If capped at hours, calc and remove hours, cap at minutes
if($cap == 'H') {
$h = intval($working/3600);
$working -= $h * 3600;
$cap = 'M';
}
// If capped at minutes, calc and remove minutes
if($cap == 'M') {
$m = intval($working/60);
$working -= $m * 60;
}
// Seconds remain
$s = $working;
// Build interval and invert if necessary
$interval = new DateInterval('PT'.$h.'H'.$m.'M'.$s.'S');
$interval->invert=$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!
Carbon could also be a nice way to go.
From their website:
A simple PHP API extension for DateTime. http://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.
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.
<?php
function cal_exp($doj1)
{
$doj1=strtotime($doj1);
$doj=date("m/d/Y",$doj1); //till date or any given date
$now=date("m/d/Y");
//$b=strtotime($b1);
//echo $c=$b1-$a2;
//echo date("Y-m-d H:i:s",$c);
$year=date("Y");
//$chk_leap=is_leapyear($year);
//$year_diff=365.25;
$x=explode("/",$doj);
$y1=explode("/",$now);
$yy=$x[2];
$mm=$x[0];
$dd=$x[1];
$yy1=$y1[2];
$mm1=$y1[0];
$dd1=$y1[1];
$mn=0;
$mn1=0;
$ye=0;
if($mm1>$mm)
{
$mn=$mm1-$mm;
if($dd1<$dd)
{
$mn=$mn-1;
}
$ye=$yy1-$yy;
}
else if($mm1<$mm)
{
$mn=12-$mm;
//$mn=$mn;
if($mm!=1)
{
$mn1=$mm1-1;
}
$mn+=$mn1;
if($dd1>$dd)
{
$mn+=1;
}
$yy=$yy+1;
$ye=$yy1-$yy;
}
else
{
$ye=$yy1-$yy;
$ye=$ye-1;
$mn=12-1;
if($dd1>$dd)
{
$ye+=1;
$mn=0;
}
}
$to=$ye." year and ".$mn." months";
return $ye.".".$mn;
/*return daysDiff($x[2],$x[0],$x[1]);
$days=dateDiff("/",$now,$doj)/$year_diff;
$days_exp=explode(".",$days);
return $years_exp=$days; //number of years exp*/
}
?>
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 https://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.
$diff_min = ( strtotime( $day2 ) - strtotime( $day1 ) ) / 60 / 60;
$total_time = $diff_min;
You can try this one.
// Create two new DateTime-objects...
$date1 = new DateTime('2006-04-12T12:30:00');
$date2 = new DateTime('2006-04-14T11:30:00');
// The diff-method returns difference in days...
$diffInDays = $date2->diffInDays($date1);
// The diff-method returns difference in hours...
$diffInHours = $date2->diffInHours($date1);
// The diff-method returns difference in mintes...
$diffInMinutes = $date2->diffInMinutes($date1);
The second part of the answer from #fidi doesn't factor in months/years.
$date1 = new DateTime('2006-04-12T12:30:00');
$date2 = new DateTime('2010-04-14T11:30:00');
$diff = $date2->diff($date1);
$hours = $diff->h;
$days = intval($diff->format('%a'));
$hours = $hours + ($days*24);
echo $hours;
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;
To pass a unix timestamp use this notation
$now = time();
$now = new DateTime("#$now");

Categories