How to calculate time in php - php

help me in calculating exact time with AM and PM
$time1 = strtotime(10:00); /// in pm
$time1 = strtotime(08:00); ///// answer should come in am calculation
is exact but not the am pm value
$count = date ('g:i ' ,strtotime($time1 . '+' . $time2));
My Problem is if i calculate time i calculate it correctly as i want but how can i set the PM and AM to time if i take 10:00 PM time add 4 hour to it now time is 02:00 AM how to get that AM PM value with time and any help with subtract time how we subtract time

Use DateTime to deal with Dates and Times with less hassle.
<?php
$time = new DateTime("10am"); // assumes 10am today
$time->modify("+4 hours");
echo $time->format("g:i A"); // outputs 2:00 PM
See the DateTime book by the author of the DateTime extension.

All you need is:
$t1 = strtotime('10am'); // 1399910400 on the date this was written
$t2 = strtotime('8am'); // 1399903200 on the date this was written
But note that that you CANNOT just do $t1 + $t2. You'll actually be doing
$t3 = 1399910400 + 1399903200
$t3 = 2799813600
And the timestamp 2799813600 corresponds to Sep 21, 2058.
You need to do:
'8am' + 2 hours => '10am';
which is
$t3 = strtotime('8am') + 60 * 60 * 2;
^^^^^^^^^^^---2hours

Related

Calculate time worked including brakes in PHP

I'm struggling to to write a PHP function that would calculate time difference between two hours (minus the brake) and the result would be in decimal format. My inputs are strings in 24-hour format (hh:mm):
$start = '07:00'; //started at 7 after midnight
$brake = '01:30'; //1 hour and 30 minutes of brake
$finish = '15:00'; //finished at 3 afternoon
//the desired result is to print out '6.5'
example 2
$start = '19:00'; //started late afternoon
$brake = '00:30'; //30 minutes of brake
$finish = '03:00'; //finished at 3 after midnight
//the desired result is to print out '7.5'
I used to have following formula in MS Excel which worked great:
=IF(D12>=F12,((F12+1)-D12-E12)*24,(F12-D12-E12)*24) '7.5 worked hours
where
D12 - Start time '19:00
F12 - Finish time '03:00
E12 - Brake time '00:30
I tried to play with strtotime() with no luck. My PHP version is 5.4.45. Please help
To provide a solution that doesn't require as much mathematics or parsing of the time values.
Assuming the day is not known, we can also account for the offset of the finish time and start time, when the start time is late at night.
Example: https://3v4l.org/FsRbT
$start = '07:00'; //started at 7 after midnight
$break = '01:30'; //1 hour and 30 minutes of brake
$finish = '15:00'; //finished at 3 afternoon
//create the start and end date objects
$startDate = \DateTime::createFromFormat('H:i', $start);
$endDate = \DateTime::createFromFormat('H:i', $finish);
if ($endDate < $startDate) {
//end date is in the past, adjust to the next day
//this is only needed since the day the time was worked is not known
$endDate->add(new \DateInterval('PT24H'));
}
//determine the number of hours and minutes during the break
$breakPeriod = new \DateInterval(vsprintf('PT%sH%sM', explode(':', $break)));
//increase the start date by the amount of time taken during the break period
$startDate->add($breakPeriod);
//determine how many minutes are between the start and end dates
$minutes = new \DateInterval('PT1M');
$datePeriods = new \DatePeriod($startDate, $minutes, $endDate);
//count the number of minute date periods
$minutesWorked = iterator_count($datePeriods);
//divide the number of minutes worked by 60 to display the fractional hours
var_dump($minutesWorked / 60); //6.5
This will work with any time values within a 24 hour period 00:00 - 23:59. If the day the times were worked are known, the script can be modified to allow for the day to be given and provide more precise timing.
To do this, convert you string times into a unix timestamp. This is an integer number of seconds since the unix epoch (00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus the number of leap seconds that have taken place since then). Do your math, then use the Date() function to format it back into your starting format:
<?php
$start = '19:00'; //started late afternoon
$break = '00:30'; //30 minutes of brake
$finish = '03:00'; //finished at 3 after midnight
//get the number of seconds for which we took a $break
//do this by converting break to unix timestamp, then extracting the hour and multiplying by 360
//and do the same extracting minutes and multiplying by 60
$breaktime = date("G",strtotime($break))*60*60 + date("i",strtotime($break))*60;
//get start time
$unixstart=strtotime($start);
//get finish time. Add a day if finish is tomorrow
if (strtotime($finish) < $unixstart) {
$unixfinish = strtotime('+1 day', strtotime($finish));
} else {
$unixfinish = strtotime($finish);
}
//figure out time worked
$timeworked = ($unixfinish - $unixstart - $breaktime) / 3600;
echo $timeworked;
?>
Another way, using DateTime. Basically, create 2 DateTime objects with the times of start and finish. To the start time, subtract the brake time, and the subtract from the result the end time.
You need to split the brake time in order to use modify().
<?php
$start = '07:00'; //started at 7 after midnight
$brake = '01:30'; //1 hour and 30 minutes of brake
$brakeBits = explode(":", $brake);
$finish = '15:00'; //finished at 3 afternoon
$startDate = \DateTime::createFromFormat("!H:i", $start);
$startDate->modify($brakeBits[0]." hour ".$brakeBits[1]." minutes");
$endDate = \DateTime::createFromFormat("!H:i", $finish);
$diff = $startDate->diff($endDate);
echo $diff->format("%r%H:%I"); // 06:30
Demo

How will i get millisecond date now vs date tommorow

i have this date and time i just want to get the millisecond until every 2:00 am.
example date/time: 10-18-2017 00:00:00 -- 2 hours before 2 am the millisecond before 2:00 am is 7200000.
what should i do or what method should i use. Thanks in advance
$datetimenow = date("m-d-Y H:i:s", strtotime('+0 hours'));
$TwoAMDay = time();
// add one day if next 2am is tomorrow
if(date('H', $TwoAMDay) >= 2) {
$TwoAMDay = $TwoAMDay + 86400;
}
$twoAMDate = date('Y-m-d 02:00:00', $TwoAMDay);
$twoAMTime = strtotime($twoAMDate);
$differenceMilliseconds = (1000 * $twoAMTime) - round(microtime(true) * 1000);

PHP Add two hours to a date within given hours using function

How would I structure the conditions to add two hours only to dates between 08:30 in the morning until 18:30 of the evening, excluding Saturday and Sunday?
In the case that a time near the border (e.g. 17:30 on Tuesday) is given, the left over time should be added to the beginning of the next "valid" time period.
For example: if the given date was in 17:30 on Tuesday, the two hour addition would result in 9:30 on Wednesday (17:30 + 1 hour = 18:30, 8:30 + the remainder 1 hour = 9:30). Or if the given date was in 17:00 on Friday, the result would be 9:00 on Monday (17:00 Friday + 1.5 hours = 18:30, 8:30 Monday + the remainder .5 hours = 9:00)
I know how to simply add two hours, as follows:
$idate1 = strtotime($_POST['date']);
$time1 = date('Y-m-d G:i', strtotime('+120 minutes', $idate1));
$_POST['due_date'] = $time1;
i have tried this this function and it works great except when i use a date like ( 2013-11-26 12:30 ) he gives me ( 2013-11-27 04:30:00 )
the problem is with 12:30
function addRollover($givenDate, $addtime) {
$starttime = 8.5*60; //Start time in minutes (decimal hours * 60)
$endtime = 18.5*60; //End time in minutes (decimal hours * 60)
$givenDate = strtotime($givenDate);
//Get just the day portion of the given time
$givenDay = strtotime('today', $givenDate);
//Calculate what the end of today's period is
$maxToday = strtotime("+$endtime minutes", $givenDay);
//Calculate the start of the next period
$nextPeriod = strtotime("tomorrow", $givenDay); //Set it to the next day
$nextPeriod = strtotime("+$starttime minutes", $nextPeriod); //And add the starting time
//If it's the weekend, bump it to Monday
if(date("D", $nextPeriod) == "Sat") {
$nextPeriod = strtotime("+2 days", $nextPeriod);
}
//Add the time period to the new day
$newDate = strtotime("+$addtime", $givenDate);
//print "$givenDate -> $newDate\n";
//print "$maxToday\n";
//Get the new hour as a decimal (adding minutes/60)
$hourfrac = date('H',$newDate) + date('i',$newDate)/60;
//print "$hourfrac\n";
//Check if we're outside the range needed
if($hourfrac < $starttime || $hourfrac > $endtime) {
//We're outside the range, find the remainder and add it on
$remainder = $newDate - $maxToday;
//print "$remainder\n";
$newDate = $nextPeriod + $remainder;
}
return $newDate;
}
I don't know if you still need this but here it is anyway. Requires PHP 5.3 or higher
<?php
function addRollover($givenDate, $addtime) {
$datetime = new DateTime($givenDate);
$datetime->modify($addtime);
if (in_array($datetime->format('l'), array('Sunday','Saturday')) ||
17 < $datetime->format('G') ||
(17 === $datetime->format('G') && 30 < $datetime->format('G'))
) {
$endofday = clone $datetime;
$endofday->setTime(17,30);
$interval = $datetime->diff($endofday);
$datetime->add(new DateInterval('P1D'));
if (in_array($datetime->format('l'), array('Saturday', 'Sunday'))) {
$datetime->modify('next Monday');
}
$datetime->setTime(8,30);
$datetime->add($interval);
}
return $datetime;
}
$future = addRollover('2014-01-03 15:15:00', '+4 hours');
echo $future->format('Y-m-d H:i:s');
See it in action
Here's an explanation of what's going on:
First we create a DateTime object representing our starting date/time
We then add the specified amount of time to it (see Supported Date and Time Formats)
We check to see if it is a weekend, after 6PM, or in the 5PM hour with more than 30 minutes passed (e.g. after 5:30PM)
If so we clone our datetime object and set it to 5:30PM
We then get the difference between the end time (5:30PM) and the modified time as a DateInterval object
We then progress to the next day
If the next day is a Saturday we progress to the next day
If the next day is a Sunday we progress to the next day
We then set our time to 8:30AM
We then add our difference between the end time (5:30PM) and the modified time to our datetime object
We return the object from the function

Compute time difference for night shift time record

I am computing for the time difference of night shift schedule using time only
lets say that I have this data:
$actual_in_time = 6:45 PM //date July 30, 2013
$actual_out_timeout = 7:00 AM //date July 31, 2013
I have to compute for the time difference where the time in should be converted to a whole time, therefore
$actual_in_time = //(some code to convert 6:45 PM to 7:00 PM)
$converted_in_time = $actual_in_time;
Now here is my code to that:
$actual_out_time += 86400;
$getInterval = $actual_out_time - $converted_in_time;
$hours = round($getInterval/60/60, 2, PHP_ROUND_HALF_DOWN);
$hours = floor($hours);
I am not getting the results I wanted. How do you compute for the time difference where the basis is just the time?
Using DateTime object
$start = new DateTime('2000-01-01 6:45 PM');
$end = new DateTime('2000-01-01 7:00 AM');
if ($end<$start)$end->add(new DateInterval('P1D'));
$diff = date_diff($start,$end);
echo $diff->format('%h hours %i minutes');
Add 1 day if your end time is less than start time.
You can use the second parameter in strtotime to get a relative time.
$start = strtotime($startTime);
$end = strtotime($endTime, $start);
echo ($end-$start)/3600;

Take current datetime and make 2 datetime variables? (6AM - 5:59AM)

I'm trying to make an events page and I want to create 2 datetime variables. They would take the current time, and create one variable at 06:00 am, and one at 05:59 am.
The issue I'm having though is with the calculations.
If a person is visiting the page on March 17, 11PM - then var1 would be March 17 06:00AM, and var 2 March 18 05:59AM.
However if a person is viewing the page on March 18 01:00 AM, then var 1 would still be March 17 06:00AM, the same goes for var2.
How would I take the below $date variable, and do the calculations for the other 2 variables?
date_default_timezone_set('America/New_York');
$date = date('Y-m-d H:i:s', time());
You can simply query the current hour to see if it's less than 6; if it is, then the start of the current logical day (based on your rules) was yesterday, 6am; otherwise it was today, 6am. Given this, strtotime can trivially get you the "start" time and adding a day to that gives you the "end" time.
date_default_timezone_set('America/New_York');
$currentHour = date('H');
if ($currentHour < 6) {
// logical day started yesterday
$start = strtotime('yesterday 06:00');
$end = strtotime('today 05:59:59');
}
else {
// logical day started today
$start = strtotime('today 06:00');
$end = strtotime('tomorrow 05:59:59');
}
echo "The current logical day started on ".date('Y-m-d H:i:s', $start);
echo " and it ends on ".date('Y-m-d H:i:s', $end);
The method for chopping the date up could be improved, but the principle works...
<?php
date_default_timezone_set('America/New_York');
$date = date('Y-m-d H:i:s', time());
// get adjusted date which subtracts 6 hours
$date_adjusted = date('Y-m-d H:i:s', time() - 60 * 60 * 6);
// chop off the time (so we are always left with the correct date now)
$date_adjusted_date = preg_split("/ /",$date_adjusted);
// Add the time element (in this case 6 AM)
$correct_date = date('Y-m-d H:i:s', strtotime($date_adjusted_date[0]."T06:00:00"));
// check the result
echo $correct_date;
?>

Categories