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;
Related
Users are allowed to pick a time for delivery up until the closing time of the store which can be 1am.
The list should should show all times up to 1am even if it is after midnight.
example 1: User arrives at 18:00 they see 18:00, 18:30, 19:00 and so on up until 00:30, 01:00
example 2: user arrives at 00:10 should see
00:30, 01:00 not
01:00, 01:30, 02:00, 02:30 etc because after midnight has become a has become a new day/date.
I am getting 30 minute time intervals between two times, it is fine as long as both times are in the same day e.g. 17:00 and 23:00. If the end time is past midnight I am not able to get the intervals so 17:00 to 01:00 doesn't give any intervals.
I understand 01:00 is another day but not quite sure how to fix it using a dynamic date. I keep thinking current day +1 will be fine unless it is after mindight then it will be an extra day if that makes sense.
Here's my code:
$timestamp = time() + 60*60;
$earliest = date("h:i ",$timestamp);
$period = new DatePeriod(
new DateTime($earliest),
new DateInterval('PT30M'),
new DateTime('01:00')
);
foreach ($period as $date) {
echo '<option value="">'.$date->format("H:i").'</option>';
}
Because 24:00 works as 00:00 I tried 25:00 but that didn't work. Any help appreciated!
UPDATE: following the answer below coverted to dynamic date, if I use date like:
$start = date('Y-m-d H:i');
$startdate = date('Y-m-d');
$end = date('Y-m-d', strtotime($startdate . ' +1 day'))." 01:00";
$period = new DatePeriod(
DateTime::createFromFormat('Y-m-d H:i','2020-04-03 17:00'),
new DateInterval('PT30M'),
DateTime::createFromFormat('Y-m-d H:i','2020-04-04 01:00')
);
After midnight it's another day added on which is problematic.
You also have to mention exact dates and not just time as 01:00. Because this way, it assumes the current date and hence you really can't have a time period between 17:00 and 01:00 on the same day. Below is how you would do it:
<?php
$period = new DatePeriod(
DateTime::createFromFormat('Y-m-d H:i','2020-04-03 17:00'),
new DateInterval('PT30M'),
DateTime::createFromFormat('Y-m-d H:i','2020-04-04 01:00')
);
foreach ($period as $date) {
echo $date->format("H:i"),PHP_EOL;
}
Demo: https://3v4l.org/5sj9Z
Update:
Since you have only times and not dates, you create DateTime objects, compare them, add 1 day to end time if it's smaller and then loop over the intervals using DatePeriod
<?php
$times = [
['18:00','01:00'],
['17:00','23:00'],
['00:10','01:00']
];
foreach($times as $time){
$start_time = DateTime::createFromFormat('H:i',$time[0]);
$end_time = DateTime::createFromFormat('H:i',$time[1]);
if($end_time < $start_time){
$end_time->add(new DateInterval('P1D'));
}
$period = new DatePeriod(
$start_time,
new DateInterval('PT30M'),
$end_time
);
echo $start_time->format('Y-m-d H:i:s'),' ',$end_time->format('Y-m-d H:i:s'),PHP_EOL;
foreach ($period as $date) {
echo $date->format("H:i"),PHP_EOL;
}
echo PHP_EOL;
}
Demo: https://3v4l.org/Ldpst
You can lose the whole timestamp calculation and have it all handled by DateTime:
// here we get the next round delivery time
$nextAvailableHalfHour = getNextHalfHourMark();
$todayMidnight = new DateTime('today'); // this creates today with time 00:00:00
$todayOneOclock = new DateTime('today 01:00'); // this creates today with time 01:00:00
// this condition says if we're now between midnight and 1 o'clock, use today
// otherwise use tomorrow
$endDate = $nextAvailableHalfHour >= $todayMidnight && $nextAvailableHalfHour <= $todayOneOclock
? $todayOneOclock
: new DateTime('tomorrow 01:00'); // create specific time tomorrow
$period = new DatePeriod(
$nextAvailableHalfHour,
new DateInterval('PT30M'),
$endDate
);
/**
* Gets the next available time with round half hour (:00 or :30).
*/
function getNextHalfHourMark(): DateTime
{
$now = new DateTime(); // create current date and time
$currentMinutes = (int) $now->format('i');
// if we are between :00 and :30
if ($currentMinutes > 0 && $currentMinutes < 30) {
// set to :30 minutes of current hour
$now->setTime($now->format('H'), 30);
// else if we are between :30 and :00
} elseif ($currentMinutes > 30 && $currentMinutes <= 59) {
// set to :00 minutes of next hour
$now->setTime($now->format('H') + 1, 00);
}
return $now;
}
The tomorrow and today strings are enabled by relative formats.
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);
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
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
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;
?>