How to calculate two hours from two times? - php

I have two times like 10:00 am and 7:00 pm.
And from this I want to get the total hours. As from that time I have to get the 9 hours.
How will I do this?
I have explode it with the : but it then subtract 7 from 10 and return the result 3 which is incorrect because it should return 9.

<?php echo strtotime('7:00 pm')-strtotime('10:00 am');?>
Get the timestamp difference
EDIT
echo (strtotime('07:00 pm')-strtotime('10:00 am'))/(60*60); //displays 9
60*60 = 1 Hrs
EDIT
$fromTime = '3:00 pm';
$toTime = '12:00 am';
$timediff = (strtotime($toTime)-strtotime($fromTime))/(60*60);
echo $timediff >= 0 ? $timediff : (24 + $timediff);

You can use the strtotime function of PHP to convert this to unix time and so you can do the further calculation with it.

I feel this will help you out more effectively
<?php echo date('H:i:s',strtotime('7:00 pm')-strtotime('10:00 am'));?>

I assume you can get hold of the am or pm information! With this information you can make an if() to make it correct!
If() it is PM, add 12 hours, if it is not PM, don't do anything.
Do this with the times you're comparing:
if (pm==1){
time+=12;
}
so 10:00 am = false it will be 10:00
and 7:00 pm = true it will be 19:00
19:00 - 10:00 = 9 hours = win.

Use DateTime interface, Its simple
$day1= new DateTime("today 01:33:26am");
$dayd2= new DateTime("today 10:40:36pm"); //Output: Hours: 21
$interval= $day1->diff($day2);
$h = ($interval->days * 24) + $interval->h;
echo "Hours: ".$h
Here
h = number of hours.
$interval->days means how many days get from difference if we get one(1) day then it's add 1*24(hours) = 24+21 = 46 hour's but here day1 and day2 contains today so, that's means 0*24 = 0 + 21 = 21
Finally Output: 21 hour's

Related

How to return specific days between two dates in PHP

I encountered a problem today that perhaps others may need help with, so I'm posting the answer here.
The client wanted me to save the dates of every Monday and Wednesday between 2 given dates.
(Neither the start nor end date actually started on a Monday or Wednesday either).
Answer is below...
You can use DateTime and DateInterval to skip directly to same day of the next week and keep track of whether it exceeds the end date or not using diff() method.
CODE:
$next_monday = new DateTime("next Monday");
$next_wednesday = new DateTime("next Wednesday");
$one_week = new DateInterval("P1W");
$end_date = new DateTime(date("Y-m-d")." +100 days");
$valid_dates = [];
while(true){
if($next_monday->diff($end_date)->invert === 1){
break;
}
$valid_dates[] = $next_monday->format("Y-m-d");
if($next_wednesday->diff($end_date)->invert === 1){
break;
}
$valid_dates[] = $next_wednesday->format("Y-m-d");
$next_monday->add($one_week);
$next_wednesday->add($one_week);
}
foreach($valid_dates as $each_date){
echo $each_date," ",date("D",strtotime($each_date)),"<br/>"; // to cross verify whether it's really Monday or Wednesday or not.
}
OUTPUT:
2018-10-01 Mon
2018-10-03 Wed
2018-10-08 Mon
2018-10-10 Wed
2018-10-15 Mon
2018-10-17 Wed
2018-10-22 Mon
2018-10-24 Wed
2018-10-29 Mon
2018-10-31 Wed
2018-11-05 Mon
2018-11-07 Wed
2018-11-12 Mon
2018-11-14 Wed
2018-11-19 Mon
2018-11-21 Wed
2018-11-26 Mon
2018-11-28 Wed
2018-12-03 Mon
2018-12-05 Wed
2018-12-10 Mon
2018-12-12 Wed
2018-12-17 Mon
2018-12-19 Wed
2018-12-24 Mon
2018-12-26 Wed
2018-12-31 Mon
2019-01-02 Wed
NOTE:
You may add 86400 seconds to start date's strtotime() and run a loop to check for each consecutive day(which will work fine). However, if you try to add 86400 * 2 or 86400 * 5 to skip past 2 or 5 days from current day, you will face issues if you don't start your loop from start date's midnight.
Instructions
First save all the required days of the week in an array. I am using short date form (D) but you could use the long form (l):
$days = ["Mon", "Wed"]; //If <PHP7 use $days = array("Mon", "Wed");
Next, convert your start and end date in to timestamps:
$starttimestamp = strtotime($start_date);
$endtimestamp = strtotime($end_date);
Next, perform a FOR loop, adding 86400 microseconds (exactly 1 day) to every cycle. This will give us a new timestamp for every day between the two days. Create a new day string for each loop:
for( $j=$starttimestamp; $j<=$endtimestamp; $j+=86400)
{
$tmpday = date('D',$j);
...
}
Finally, perform an in_array check ( eg. if needle in haystack ) to see whether the DAY matches any of our required days:
for( $j=$starttimestamp; $j<=$endtimestamp; $j+=86400)
{
$tmpday = date('D',$j);
if(in_array($tmpday, $avail_days) ){
echo date('Y-m-d',$j);
}
}
That's all there is to it. The entire code can be seen below. I hope this helps someone else in the future:
Entire Code
$avail_days = ["Mon", "Wed"]; //If <PHP7 use $days = array("Mon", "Wed");
$starttimestamp = strtotime($your_start_date);
$endtimestamp = strtotime($your_end_date);
for( $j = $starttimestamp; $j <= $endtimestamp; $j += 86400 )
{
$tmpday = date('D',$j);
if(in_array($tmpday, $avail_days) ){
echo date('Y-m-d',$j); //This date has a day that matches your required days!
}
}

Calculate nearest hours to 00:00 in PHP

How can I calculate the nearest hours to midnight time 00:00 regardless of date in PHP. For example:
If time is 22:00 then 2 hours are required to reach 00:00
If time is 04:00 then -4 hours are the nearest to reach 00:00
Currently I have the following PHP function:
<?php
$ts1 = strtotime('00:00');
$ts2 = strtotime('04:00');
$diff = ($ts1 - $ts2) / 3600;
?>
But this won't be helpful much in the above.
If you have the php Datetime class available you can calculate the difference between two DateTimes.
$time1 = new \DateTime('00:00');
$time2 = new \DateTime('04:00');
$diff = $time1->diff($time2, true);
$hourDifference = 0;
if ($diff->h < 12) {
$hourDifference = -$diff->h;
} elseif ($diff->h > 12) {
$hourDifference = 24 - $diff->h;
} else {
$hourDifference = 12; // kann be positive or negative
}
And you'll get a DateInverall object where you can access, hours, minuts, seconds and compare them with normal php operators.
If you'r not too interested in minutes;
1. Extract minutes.
check if minutes is > or <=30
if greater, 'store' 1
2. Extract hour
check if hour is greater than 12
if not, add 12 (store flag also to say it will be minus)
3. if greater (ref. Step 1), add 1 to extracted hour.
4. 24 - extracted hour is your interval.
Please note, this may be reduced/ simplified greatly.
Your interval (should) be correct to the nearest half hour
The answer depends on the date (not only the time). This is because of daylight saving time changes. For example might 02:59 being closer to 00:00 then 21:01 on the time where daylight saving time will set back hour.

Shortest logic to calculate hours from overlapped time php

I am trying to calculate no of hours of user. If many schedules assigned to him.
Schedules are -
10:00 AM - 12 pm
11 am - 12 pm
9 am - 12 pm
8 am - 5 pm
These schedules are assigned to a user.
I have to calculate no of hours how much time he is spending on these schedules.
Is there any shortest method to calculate this ?
I want answer = 8 hours. I dnt want to calculate the diff I want no of hours.
NO I want the result 8.. I explain why
10:00 AM - 12 pm --- 2 hour,
11 am - 12 pm ---- 1 hour already added ,
9 am - 12 pm ----- 3 hour but 10 - 12 already added so 1 hour,
8 am - 5 pm ---- 8 hours
Use this:
$minutes_diff = round(abs(strtotime($time1) - strtotime($time2)) / 60);
Or this:
$time1="7.30 AM";
$time2="8.30 PM";
$d1= strtotime($time1);
$d2= strtotime($time2);
$diff=$d2-$d1;
//Print the difference in hours : minutes
echo date("H:i",$diff);
I wrote this script to sum the total amount of hours in a work schedule from start of the work day until the end:
// $key['date'] contains a date format of 'yyyy-mm-dd'
// $key['start'] and $key['end'] contains a time of format hh:mm:ss
$start = new DateTime( $key['date'] .'T' . $key['start'] );
$end = new DateTime( $key['date'] .'T' . $key['end'] );
// difference returns the differential between start and end resulting in number of hours worked
$difference = $start->diff( $end );
// Additionally, I would like 1 hour and 15 minutes to result in 1.25 instead of 1.15 and so on. For this I used this:
$minute = $difference->format( '%i' )*1.666666666667;
$total = $difference->format( '%h' ) . '.' . $minute;

PHP DateTime: How to get "diff" between two times using 24 hour clock format

Trying to subtract two times:
$obtime = "2310";
$runtime = "0048";
$run=new DateTime($runtime);
$ob=new DateTime($obtime);
$interval= $run->diff($ob);
$age=$interval->format('%H%I');
print "Age is: $age\n";
The above will output 2222, meaning 22 hours and 22 minutes difference.
Of course, we know that clocks go forward, and 0048 is only 1 hour 38 min after 2310.
Is there a better way to find the time difference between two "24hr" times?
how about
$obtime = strtotime("2310");
$runtime = strtotime("0048");
echo gmdate("H:i:s", $obtime - $runtime);
Thanks gwillie. That did not work as you have it, but, it's because of the order of the time variables.
If you subtract the OLDER time from the NEWER time, it works.
This outputs 1 hr 38 min:
$obtime = strtotime("2210");
$runtime = strtotime("2348");
echo gmdate("H:i", $runtime - $obtime);
While this outputs 22 hr 22min:
$obtime = strtotime("2210");
$runtime = strtotime("2348");
echo gmdate("H:i", $obtime - $runtime);
Good to know that this method can go forward or backward, while the original method I was using is not that "smart".

PHP : How to calculate the remaining time in minutes?

Suppose the target time is 4.30 pm and the current time is 3.25 pm , how will i calculate the minutes remaining to reach the target time ? I need the result in minutes.
session_start();
$m=30;
//unset($_SESSION['starttime']);
if(!$_SESSION['starttime']){
$_SESSION['starttime']=date('Y-m-d h:i:s');
}
$stime=strtotime($_SESSION['starttime']);
$ttime=strtotime((date('Y-m-d h:i:s',strtotime("+$m minutes"))));-->Here I want to calcuate the target time; the time is session + 30 minutes. How will i do that
echo round(abs($ttime-$stime)/60);
Krishnik
A quick calculation of the difference between two times can be done like this:
$start = strtotime("4:30");
$stop = strtotime("6:30");
$diff = ($stop - $start); //Diff in seconds
echo $diff/3600; //Return 2 hours. Divide by something else to get in mins etc.
Edit*
Might as well add the answer to your problem too:
$start = strtotime("3:25");
$stop = strtotime("4:30");
$diff = ($stop - $start);
echo $diff/60; //Echoes 65 min
Oh and one more edit:) If the times are diffent dates, like start is 23:45 one day and end is 0:30 the next you need to add a date too to the strtotime.

Categories