Calculate total hours between 2 time stamps - php

I have two variables:
$start_time = '9:36';
$end_time = '12:47';
How would i calculate the amount of hours between the two times and store them in a variable like this:
$total_hours = 3;
I have read that you need to convert the times first. Also there will be no need for date as this will all be on the same day.
Any help would be appreciated

if you only need to calculate the hours difference you could use the datetime class especifically the function date_parse_from_format where you just need to provide the format as seed and then what you need to parse give that calculate the difference
Edit 1
you could do something with less overhead:
$start_time = '9:36';
$end_time = '12:47';
$today = date('Y-d-m');
$start = strtotime($today . ' ' . $start_time);
$end = strtotime($today . ' ' . $end_time);
$diff = floor(($end - $start) / 3600);
// or if you don't need the exact hours
$diff = ($end - $start) / 3600;

Convert time string tor timestamp: strftime
Take the difference, and
a. Use date to get the hours (H) value
b. Divide with 3600 and round as much digit as you
need
$total_hours = (int)date('G', abs(strtotime($time2)-strtotime($time1)));

See below
$start_time = '9:36';
$end_time = '12:47';
$v = strtotime($end_time) - strtotime($start_time);
echo date("h:i", $v);
Outputs
03:11
http://php.net/manual/en/function.strtotime.php and http://php.net/manual/en/function.date.php

This solves your problem:
$start = explode(':', $start_time);
$end = explode(':', $end_time);
$total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
See this codepad for a proof.
This solution assumes both hours are from the same day.

Why are you guys making it complicated? It can be done in a one-liner code:
abs((strtotime("11:00 AM") - strtotime("12:00 PM")) / 3600)
Result:
1
Please note that this assumes that both time are in the same day, although it will still work if both are from different dates.

Related

Calculate percentage between dates in php

I want to calculate the percentage (from 0 to 100) of the time elapsed between two dates (start and end) according to the current date.
For example:
$start_date = "01/01/2018";
$end_date = "31/12/2018";
$today = "30/06/2018";
Expected output:
Percentage: 50
Any idea? Thanks
You could convert all dates to timestamps and do the math from there. strtotime() will convert the dates for you, but that will interpret your dates with slashes in the english format (MM/DD/YYYY) instead of (DD/MM/YYYY). If you replace the slashes with dashes, it will read it in the DD-MM-YYYY format.
$date_timestamp = strtotime(str_replace('/', '-', $date));
Then it's just a matter of:
$total = $end_date - $start_date;
$part = $todays_date - $start_date;
$percent = $part/$total * 100;
You'd need at least three variables:
$fromDate = strtotime("01/01/2018 ");
$currentDate = time();
$toDate = strtotime("01/01/2019");
//days between From and To
$datediffA = round(($toDate- $fromDate) / (60 * 60 * 24));
//days between From and Current
$datediffB = round(($currentDate- $fromDate) / (60 * 60 * 24));
echo $datediffA;
echo $datediffB;
Will output:
365
320
Now knowing these numbers you can go on and find the percentage of one to another.
$percentage = ($datediffB*100)/$datediffA;
echo $percentage;
Will output:
87.671232876712%
Date("z") gives you the day of the year.
Your "today" returns 180.
If we assume start and end is the start and end of current year then all you need is the date("z") to calculate the percentage.
Round the value to desired format and echo the percentage.
$today ="30/06/2018";
echo round(date("z", strtotime(str_replace("/", "-", $today)))/365*100,0) . "%";
// 49%
https://3v4l.org/EG6lt
I assume 365 days is enough accurate as a year.
You can use 365 + date("L") instead of only 365 in the code above and it will add one if it's a leap year.
Meaning:
echo round(date("z", strtotime(str_replace("/", "-", $today)))/(365 + date("L"))*100,0) . "%";

divide PHP time (h:i)

I have an employee timesheet where durations are divided by the number of days an employee works.
E.g 25:00 over 3 days = 25:00/3=08:20
I have tried the simple divide query above, however this does not show a result. Is it possible to divide a h:m string?
Best approach would be to convert to seconds and use date to display it.
$time ="25:00";
$days = 3;
list($hours, $minutes) = explode(":", $time);
$minutes += $hours*60;
$seconds = $minutes*60;
date_default_timezone_set ("UTC");
echo "new time: " . date("h:i", $seconds/$days);
See the result here

Add minutes to strtotime

If i have a varible
// in minutes
$min = 40;
And i want to add it to a strotime formatted time
$strtTime = $strtotime('now') + $min;
whats the correct way to do this?
You can do this:
strtotime("+{$min} minutes");
There's not much to it:
echo strtotime("+40 minutes");
See it in action
Well, look at the documentation. It tells you how to use the function.
$future = strtotime('+40 minutes');
You can also be a little more concrete and include where to start from.
$future = strtotime('now + 40 minutes');
While the above is a lot easier you could also do it manually. It just involves some basic arithmetic:
$now = time(); // Seconds since 1970-01-01 00:00:00
$minutes = 40;
$seconds = ($minutes * 60); // 2400 seconds
$future = ($now + $seconds);
$min = 40;
And i want to add it to a strotime formatted time
$strtTime = strtotime("+".$min." minutes", strtotime('now'));//eg +40 minutes

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";

Difference between dates

I want to calculate the difference between two times, one of which is the current time, and the other is just in the format HH:MM, always in the future.
If I just subtract $futuretime from $now, it should, of course, be a positive number.
This works fine until...
If $now is in the afternoon or evening and $futuretime is, say, 7AM next morning, how can I force it to understand the the time is always going to be in the future?
(It's for working out the time of something that occurs about every half an hour during working hours, and then stops until the following morning)
Thanks in advance!
Simply add a whole day to the difference if it is negative. Assuming that $now and $futuretime are timestamps (stored in seconds since midnight), simply do the following:
$diff = $futuretime - $now;
if ($diff < 0)
$diff += 24 * 3600;
If they are in HH:MM format:
list($future_hours, $future_mins) = explode(":", $futuretime);
$futuretime = $future_hours * 60 + $future_mins;
list($now_hours, $now_mins) = explode(":", $now);
$now = $now_hours * 60 + $now_mins;
$diff = $futuretime - $now;
if ($diff < 0)
$diff += 24 * 60;
Of course the latter case returns the difference in minutes, while the former returns the difference in seconds.
Edit: as Andy noted below in the comments, this is not a good solution if you care about changes in DST. See his solution for a better approach.
If you're on PHP 5.3+, use PHP's DateTime:
$d1 = new DateTime('14:52:10');
$d2 = new DateTime('12:12:10');
$diff = $d1->diff( $d2 );
var_dump( $diff );
You can simply convert both dates to timestamp, do the calculations and convert it to required format, i.e. days, hours and minutes. it's quite simple.

Categories