Calculating time difference for fixed hour - php

I want to calculate the time difference from now (lets say 18:30:00) till this evening at 20pm.
$today = date('Y-m-d', time());
$remain = strtotime($today. " 00:00:00 + 20 hours") - time();
$remain = date('H:i:s', $remain);
I get a result which is one hour larger (02:30:00) than the actual result (01:30:00). I tried setting time zones but it's always the same result.

Using the DateTime object, you can do this easily:
$d1 = new DateTime('2015-04-23 18:30');
$d2 = new DateTime('2015-04-23 20:00');
$interval = $d2->diff($d1);
echo $interval->format('%H:%i hours');

Related

How to find the Time Difference between a PM time and AM time?

In my form there are 2 Time Pickers where user can select a from time and to time. It doesn't have a date associated with it. And for a report generating purpose I've to calculate the time difference between them. It works perfectly to if the From and to Time is "06:00 to 10:00" but if the from and to time is "21:00 to 02:00" I get a time difference of 19 hours. Could you please help me to fix this.
For this case "21:00 to 02:00" the time difference should be 5 hours.
This is the Code
$datetime1 = new \DateTime('09:30 PM');
$datetime2 = new \DateTime('02:00 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
exit;
The difference becomes negative If $totime is less than $fromtime.
DateInterval->invert == 1 indicates that. This is used with this short solution to correct the result.
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$diff = date_create($fromtime)->diff(date_create($totime));
$hours = $diff->invert ? 24-$diff->h : $diff->h;
echo $hours; //5
Since you have 2 date pickers one for from time and another to time, the former will always be smaller than the latter. Hence when from time is larger than to time it means user has selected to from the next day. If we don't add a date for calculating difference, PHP will assume today's date by default. We can easily fix this by adding a condition to compare the times and prepend the dates accordingly. Below is the updated code.
<?php
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$now = new \DateTime();
$today = $now->format('Y-m-d'); // Store current date
$now->add(new DateInterval('P1D')); // Add one day to current date to get next date
$nextDay = $now->format('Y-m-d'); // Store next date
if($fromtime > $totime) // If from time is bigger than to time, it means to is a next day
{
$fromdatetime = "$today $fromtime";
$todatetime = "$nextDay $totime";
}
else
{
$fromdatetime = "$today $fromtime";
$todatetime = "$today $totime";
}
$datetime1 = new \DateTime($fromdatetime);
$datetime2 = new \DateTime($todatetime);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
?>

Cannot calculate the time difference using PHP

I need to calculate the datetime difference in minutes using PHP. I am explaining my code below .
$date='10-03-2018 03:44 PM';
$endTime = strtotime($date);
$currentDate=date("d-m-Y h:i A");//10-03-2018 03:53 PM
$currentTime = strtotime($currentDate);
echo (round(abs($currentTime - $endTime) / 60,2));//25344617
Here I need to calculate the difference in minutes but the differnce value is more where the expected time difference should be 9 but as per my code I am getting the wrong value.
Let the PHP DateTime class with diff() method do the work with time calculations.
$now = '10-03-2018 03:53 PM'; // or use simply 'now' for current time
$endTime = '10-03-2018 03:44 PM';
$datetime1 = new DateTime($now);
$datetime2 = new DateTime($endTime);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%i minutes'); // 9 minutes
See it live: https://eval.in/969615

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');

calculate day difference between two unix timestamps at boundary values

I have two timestamps created against dates 02/09/2014 11:30pm and 03/09/2014 12:00am.
There is only 30 minutes difference between these timestamps but as date has changed from O2 October to 03 October, it should be calculated as a day.
My code is
$current_time_zone = isset($_COOKIE['IANA_timezone_key']) ? $_COOKIE['IANA_timezone_key'] : "";
$d1 = new DateTime(date('Y-m-d'), timezone_open($current_time_zone));
$d2 = new DateTime(date('Y-m-d'), timezone_open($current_time_zone));
$d1->setTimestamp($row["transitions_date"]); // $row["transitions_date"] has timestamp value
$d2->setTimestamp($curr_transition_in_date); // $curr_transition_in_date has timestamp value
$diff = date_diff($d1, $d2);
$day_difference = $diff->days;
Any help will be highly appreciated.
You could not expect your desired day difference from the returning object of date_diff() as it is based on the actual time difference. The easiest way would be to adjust it yourself.
$d1 = new DateTime(date('Y-m-d'));
$d2 = new DateTime(date('Y-m-d'));
$d1->setTimestamp($row["transitions_date"]);
$d2->setTimestamp($curr_transition_in_date);
$diff = date_diff($d1, $d2);
$day_difference = $diff->days;
echo 'Actual output from date_diff: '.$day_difference;
echo '<br>';
if($d2->format('H:i:s') < $d1->format('H:i:s')){
$day_difference++;
}
echo 'Corrected output: '.$day_difference;
Demo 1 for the different day, but same month and year.
Demo 2 for the same day, but different month and year.
Demo 3 for the same output.

Check how many days were passed since the last update in PHP

I am trying to check how many days were passed since the user last entered the system. I get the last time he\she entered from mysql table column (datetime). so I wrote :
$user_last_visit = $user_info['last_updated']; // 2013-08-08 00:00:00
$user_last_visit_str = strtotime($user_last_visit); // 1375912800
$today = strtotime(date('j-m-y')); // 1250114400
$diff = $today - $user_last_visit_str;
Where $user_info['last_updated'] has the last time he\she visited with the value of 2013-08-08 00:00:00.
After strtotime I get $user_last_visit_str equals to 1375912800
$today has the value of 9-08-13 and after strtotime I get 1250114400.
Some reason $diff = $today - $user_last_visit_str; is negative instead of getting a positive value with 24*60*60*1000 (one day = 24*60*60*1000 ms).
Any ideas?
A simple solution using diff:
echo date_create()->diff(date_create($user_last_visit))->days;
If all else fails, just do:
$diff = floor((time() - $user_last_visit_str) / (60 * 60 * 24));
you can use below code to get date diff, here i given static last date which is 15th july 2013, and taking different from current date.
$last_date = date('y-m-d', strtotime('15th july 2013'));//here give your date as i mentioned below
//$last_date = date('y-m-d', strtotime($your_old_date_val));
$current_date = date('y-m-d');//
echo $date_diff = strtotime($current_date) - strtotime($last_date) ;
echo $val = 60*60*24;
$days_diff = $date_diff / $val;
echo $days_diff;
Try this:
$user_last_visit = $user_info['last_updated']; // considering the value of user last visit is 2013-08-08 00:00:00 which indicates year, month, day, hour, minute, second respectiveliy
$user_last_visit_str = strtotime($user_last_visit);
$today = time();
$diff = $today - $user_last_visit_str;
$no_of_days = ($diff / (60*60*24));
Try using a DateTime object if your version of PHP supports it:
$user_last_visit = DateTime::createFromFormat('Y-m-d H:i:s', $user_info['last_updated']);
$today = new DateTime();
$diff = $today->diff( $user_last_visit, true );
echo $diff->days;
$diff will be a DateInterval object.
try reversing the $today assignment, like so:
$today = strtotime(date('y-m-j'));
that worked for me.

Categories