How to add an odd day to a time in PHP? - php

How to add an odd day to a time in PHP?
Like add 1.5 day? Any idea?
When I try like 1.5 or 1,5 then it's adding 15 days.
Is there anyway to add odd day to time?

If there are fractions of days, they can be converted to seconds and then added.
$days = 1.5;
$seconds = (int)(86400 * $days);
$dt = new Datetime('2022-04-01');
$dt->modify($seconds.' Seconds'); //add
echo $dt->format('Y-m-d H:i');
//2022-04-02 12:00
Also works with $days = 1.25; This then returns 2022-04-02 06:00 as a result.
Or $days = 1.1 returns 2022-04-02 02:24.

Following is the one approach you can do first add an exact number of days(non-fractional part) and then add fractional value in hours.
For example, If you want to add 1.5 days then add 1 day and 12 hours.
echo date("Y-m-d H:i:s", strtotime('+1 Day +12 Hours'))

Related

Carbon show time different days hours minutes second

i try to make time difference with carbon
$dt = Carbon::parse('2018-07-15 00:00:00');
$now = Carbon::now('Asia/Dubai'); //set current time
$seconds = $now->diffInSeconds( $dt ); //difference turn into second
$days = $dt->diffInDays($dt->copy()->addSeconds($seconds));
$hours = $dt->diffInHours($dt->copy()->addSeconds($seconds)->subDays($days));
$minutes = $dt->diffInMinutes($dt->copy()->addSeconds($seconds)->subHours($hours));
$days result are 12 (its right).
$hours result are 8 (seems not right).
$minutes result are 17299 (clearly wrong).
how to get the result for example 12 day 5 hours 45 minutes
Actually functions like diffInSeconds give total difference in seconds that's why the number is so large,to get the minutes for the time difference right you can use -:
$minutes = ($now->minute - $dt->minute);

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

Correct no of days/weeks between 2 days?

I have created a function to work out the amount of days and then weeks between 2 dates, in the example below there is 35 days resulting exactly 5 weeks, however the function is returning just short of this at 4.8571428571429 - the division is killing the remainder and coming out at 4.
I could use the ceil function to round it up to 5 but is this this a safe method for all dates? or is there a better way to do it?
$date1 = new DateTime('2015-02-23');
$date2 = new DateTime('2015-03-29');
$diff = $date2->diff($date1)->format("%a");
$weeks = $diff / 7;
return $weeks;
$date2->add(new DateInterval('P1D'));
Use this line after your $date2 initialisation.
Why will this work?
If you count, you have 34 days now: FROM 23-02 0:00 TILL 29-03 0:00.
If you want to count this last day also (to have 35 days), you'll need to add an extra day.
Add a single day to $date2
$date1 = new DateTime('2015-02-23');
$date2 = new DateTime('2015-03-29');
$date2->add(new DateInterval('P1D'));
$diff = $date2->diff($date1)->format("%a");
$weeks = $diff / 7;
return $weeks;
However, you still don't have a whole number of weeks difference with your original dates

string to time not working as expected

I can't figure out why this is happening but when I added -10 mins to a time... it doesn't work.
This is a simplified version:
$time = '08:30';
$time_minus_10m = strtotime($time) + strtotime("-10 min");
echo '<b>'.$time.'</b> -10 mins is <b>'.date('H:i', $time_minus_10m).'</b>';
It outputs:
08:30 -10 mins is 01:05
but should output:
08:30 -10 mins is 08:20
Have you tried combining them?
$time_minus_10m = strtotime("$time -10 minutes");
In isolation, strtotime('-10 minutes') just gives you the time 10 minutes before the current time; adding that to any other time doesn't really make sense anymore :)
If you already have an existing timestamp to anchor against, you can pass that as the second parameter to be used instead of the current time.
Because you are subtracting 10 minutes from the current time since you don't provide the time in the strtotime() call. Try:
$time_minus_10m = strtotime("-10 min", strtotime($time));
$time = new DateTime('08:30');
$cloned_time = clone $time;
$time_minus_10m = $cloned_time->modify('-10 min');
echo '<b>'.$time->format('H:i').'</b> -10 mins is <b>'.$time_minus_10m->format('H:i').'</b>';

Calculating countdown between now and x amount of days ahead to cetain time of day

I am completely stuck here. I am trying to get how many days hours and minutes to echo from a calculation from the current time to 7 days from now at 6pm. I look at the amount of seconds produced from my $difference variable and when I do the math to convert it to days hours and minutes it is correct but for some reason when I call the specific days, hours, and minutes in my output statement it is incorrect. What am I doing wrong. Here is the code.
<?php
date_default_timezone_set('America/New_York');
$nextWeek = strtotime('+7 days');
$m = date('n', $nextWeek);
$d = date('j', $nextWeek);
$y = date('Y', $nextWeek);
$difference = mktime(18,0,0,$m,$d,$y) - time();
echo '<p>Current date and time is' .date(' l F d, Y '). 'at '.date('g:i a').' You have an appointment in a week on '.date(' n/j/Y ', $nextWeek).' at 6pm. There are ' .date(' j ', $difference).' days, ' .date(' g ', $difference).' hours, and ' .date(' i ', $difference).' minutes until your appointment.</p>';
echo mktime(18,0,0,$m,$d,$y),"\n";
echo $difference;
?>
The problem is that you're using PHP's date() function on a number that doesn't represent a date. Your variable $difference represents the difference between the two dates, in seconds. To get the right output, you should write your own function to convert these seconds to number of days, hours, minutes, etc.
It might look something like this:
function getTimeText($seconds)
{
$return = array();
$return["days"] = floor($seconds/86400); // 86400 seconds in a day
$seconds -= ($return["days"]*86400);
$return["hours"] = floor($seconds/3600); // 3600 seconds in an hour
$seconds -= ($return["hours"]*3600);
$return["minutes"] = floor($seconds/60); // 60 seconds in a minute
return $return;
}
Try checking out this. The example part way down the page shows you how to find the difference between two dates in days. You should be able to use it to return the difference between the current time and the time in 7 days at 18:00 by changing the format.

Categories