I have looks like simple task, but I can't solve the problem. I would like to count two times in seconds by PHP ($time + $time1) but my result is +1hour (+1day). Why?
$hours="00";
$minutes="34";
$seconds="13";
$hours1="00";
$minutes1="35";
$seconds1="11";
$time=($hours*3600)+($minutes*60)+$seconds; // 2053 seconds
$time1=($hours1*3600)+($minutes1*60)+$seconds1; // 2111 seconds
$sum=$time+$time1; // 4164 seconds
$format=date('H:i:s', $time); // 01:34:13
$format1=date('H:i:s', $time1); // 01:35:11
$formatsum=date('H:i:s', $sum); // 02:09:24
$format has to be 00:34:13 not 01:34:13
If I add the days date(' d H:i:s', $time); result is 01 01:34:13
My task is 00:34:13 + 00:35:11 with result 01:09:24 not 02:09:24
Do I something wrong with time formating? Why it gives me +1day and +1hour to the result?
Change this:
$format=date('H:i:s', $time); // 01:34:13
$format1=date('H:i:s', $time1); // 01:35:11
$formatsum=date('H:i:s', $sum); // 02:09:24
To:
$format=gmdate('H:i:s', $time); // 00:34:13
$format1=gmdate('H:i:s', $time1); // 00:35:11
$formatsum=gmdate('H:i:s', $sum); // 01:09:24
gmdate — Format a GMT/UTC date/time
php doca gmdate
You should check your time zone. The time calculated is by your local time zone. As example, for
$time=($hours*3600)+($minutes*60)+$seconds; // 2053 seconds
$format=date('H:i:s', $time); // 02:34:13
For +2GMT
The result is 01:34:13, because your default timezone is set to UTC +1.
Use gmdate() function instead of date() if you want to convert a timestamp to a UTC date:
$hours = "00";
$minutes = "34";
$seconds = "13";
$hours1 = "00";
$minutes1 = "35";
$seconds1 = "11";
$time = ($hours * 3600) + ($minutes * 60) + $seconds; // 2053 seconds
$time1 = ($hours1 * 3600) + ($minutes1 * 60) + $seconds1; // 2111 seconds
$sum = $time + $time1; // 4164 seconds
$format = gmdate('H:i:s', $time); // 00:34:13
$format1 = gmdate('H:i:s', $time1); // 00:35:11
$formatsum = gmdate('H:i:s', $sum); // 01:09:24
Also, I'm not sure what you want to achieve with your code, but there are better tools for date/time manipulation than manual addition of seconds. Check out DateTime and DateInterval classes from PHP standard library.
Related
I need to add a time stored in strong (format: hh:mm) to a date timestamp which before have no hours information (e.g. 2018-06-12 00:00:00). How to do it?
I would like to do this:
$startTime = "11:45";
$startDate = 1528754400; // 2018-06-12 00:00:00
$startDate = $startDate + $startTime; //2018-06-12 11:45:00
You can do some simple math and get there. Multiple minutes by 60 and hours by 3600 and you'll get the number of seconds the hours/minutes take up.
$startTime = "11:45";
$startDate = 1528754400;
$time = explode(':', $startTime);
$minutes = $time[1] * 60;
$hours = $time[0] * 3600;
Then just piece it back together. (the timestamp is the number of seconds since 1970 so just adding to it should be fine)
$startDate + $minutes + $hours
https://3v4l.org/U2jHL
An alternative approach would be using the datetime class.
$startTime = "11:45";
list($hours, $minutes) = explode(':', $startTime);
$date = new DateTime(date('Y-m-d', 1528754400));
$date->add(new DateInterval('PT' . $hours .'H' . $minutes . 'M'));
https://3v4l.org/D51XB
Just came across with this using strtotime:
$startTime = "11:45";
$startDate = 1528754400; // 2018-06-12 00:00:00
$startTimeTmp = explode(":",$startTime);
$finalTimestamp = strtotime("+".$startTimeTmp[0]." hours ".$startTimeTmp[1]." minutes", $startDate);
I have two times: a starting time and the duration. I want to subtract the duration from the starting time. The time I read from an mysql db and is already formatted. My code:
$start= $row["start"]; //output is for e.g. 08:00:00
$dur = $row["duration"]; //output is for e.g. 01:00:00
$sub = $start - $dur;
// I want the output to be 07:00:00
// the result now is 7 and I got an error (non well formed numeric value)
Can someone help me?
Alternatively you can achieved like this
$date = "1970-01-01";
$start = $date." ".$row["start"];
$dur = $date ." ".$row["duration"];
$date1=date_create($start);
$date2=date_create($dur);
$diff=date_diff($date1,$date2);
echo $diff->format("%H:%I:%S");
$start= "08:00:00";
$dur = "01:00:00";
$diff = differenceInHours($start, $dur);
echo convertTime($diff);
function differenceInHours($startdate,$enddate){
$starttimestamp = strtotime($startdate);
$endtimestamp = strtotime($enddate);
$difference = abs($endtimestamp - $starttimestamp)/3600;
return $difference;
}
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
You should always save date in your database in the appropriate format. And not as a "already formated" value. Except in very specific case.
Anyway, to solve your problem you can do soemthing like this
$start = new DateTime('08:00:00');
$duration = new DateTime('01:00:00');
$interval = date_diff($start, $duration);
echo $interval->format('%H:%I:%S'); //ouput will be 07:00:00
I have a system which I need to add a certain amount of fractional hours.
I've been searching and this is what I got, by far it's the most accurate method, but still doesn't give me the answer I need
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = array();
$time = explode(".", $hours);
$time [1] += $time [0]*60;
$now->modify("+".$time[1]." hours");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer ->format('Y-m-d H:i:s');
The answer that I want to reach is "2017-11-09 11:00:00" and I receive "2017-10-25 12:22:23" instead
Adding the hours is not correct. When you multiply hours times 60 it will make minutes.
This code should work.
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = explode(".", $hours);
$time[1] += $time[0]*60;
$now->modify("+".$time[1]." minutes");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer->format('Y-m-d H:i:s');
Result is 2017-10-30 09:46:00
You should use DateInterval php class to create an inverval with x seconds from your $hours variable.
Then you just have to use the datetime add interval method to modify your date
Please take a look a this example
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
var_dump($now);
$timeParts = explode(".", $hours);
// Where 23 is a percentage of on hour
$minutes = $timeParts[0] * 60 + round($time[1] * 60 / 100);
// Where 23 is the number of minutes
$minutes = $timeParts[0] * 60 + $time[1];
$interval = new DateInterval(sprintf('PT%dM', $minutes));
$now->add($interval);
echo $now->format('Y-m-d H:i:s');
return $now;
}
Use date_add
date_add($now, date_interval_create_from_date_string($tempo[1]' hours'));
or as object:
$now->add( DateInterval::createFromDateString($tempo[1].' hours'));
Say I have the following as a string:
$timeLeft = 00:02:30
I want to be able to subtract 1 second, turning it into 00:02:29.
I have tried
$timeLeft - 1;
But it does nothing.
How can I make it so I can subtract seconds from a string?
You need to convert it to a time, subtract 1 second and reformat, e.g.:
$timeLeft = '00:02:30';
$time = DateTime::createFromFormat('H:i:s', $timeLeft);
$time->sub(new DateInterval('PT1S'));
$timeLeft = $time->format('H:i:s');
Below is dirty code that performs the transformation "manually" by converting the time into seconds in case PHP 5.3+ is not available. It'll certainly misbehave it the number of seconds subtracted is greater than the total.
$timeLeft = '00:02:30';
list($hours, $minutes, $seconds) = explode(':', $timeLeft);
$seconds += $hours*3600 + $minutes*60;
unset($hours, $minutes);
$seconds -= 1; //subtraction
$hours = floor($seconds/3600);
$seconds %= 3600;
$minutes = floor($seconds/60);
$seconds %= 60;
$timeLeft = sprintf("%'02u:%'02u:%'02u", $hours, $minutes, $seconds);
Using strtotime is a good practical solution, but you have to watch out for DST changes:
$tz = date_default_timezone_get(); // save old timezone
date_default_timezone_set('UTC'); // switch to UTC
echo date('H:i:s', strtotime($timeleft) - 1); // perform calculation
date_default_timezone_set($tz); // restore old setting
I use this function to set a time date("Y-m-d H:i:s", strtotime("+2 minutes"). Now I want to compare that value with the current time to find the amount of seconds it's left.
For example compare: $next_action = 2011-01-16 18:03:00 and $now = 2011-01-16 18:01:23. To find the amount of seconds.
strtotime can convert mysql timestamps to unix timestamps. so you just convert both of them to UNIX timestamps and subtract one from other, and you'll get the difference in seconds.
$next_action = "2011-01-16 18:03:00";
$now = "2011-01-16 18:01:23";
echo strtotime($next_action)-strtotime($now);
Why did you convert them to "Y-m-d H:i:s" in the first place? Unix timestamps are much easier to work with.
$start_time = date("Y-m-d H:i:s", strtotime("+2 minutes"));
$time_diff = (time() - strtotime($start_time)); // difference in seconds
$seconds = $time_diff % 60;
$minutes = ($time_diff - $seconds) % (60 * 60);
$hours = ($time_diff - ($minutes * 60) - $seconds) / (24 * 60 * 60);
Untested, but it would probably go something like this.