In my PHP application I want to calculate the sum of two time variables. I am looking for something like this example.
$time1 = 15:20:00;
$time2 = 00:30:00;
$time = $time1+$time2;
If the answer you expect is 15:50:00 and you want to use strtotime and date functions, you need to subtract the seconds $time1 and $time2 share when you transform them to unix timestamps:
$time1 = '15:20:00';
$time2 = '00:30:00';
$time = strtotime($time1) + strtotime($time2) - strtotime('00:00:00');
$time = date('H:i:s', $time);
The best way to do this is most likely to use strtotime to convert them to timestamps and then do the adding together:
$o = strtotime($time1)+strtotime($time2);
If I remember right strtotime does support this format.
Otherwise you will need to filter it out yourself.
Following answer does not return correct value. It is summing integers but not returned correct time.
$o = strtotime($time1)+strtotime($time2);
I created a function to get calculated time as follows.
public function addTwoTimes($time1 = "00:00:00", $time2 = "00:00:00"){
$time2_arr = [];
$time1 = $time1;
$time2_arr = explode(":", $time2);
//Hour
if(isset($time2_arr[0]) && $time2_arr[0] != ""){
$time1 = $time1." +".$time2_arr[0]." hours";
$time1 = date("H:i:s", strtotime($time1));
}
//Minutes
if(isset($time2_arr[1]) && $time2_arr[1] != ""){
$time1 = $time1." +".$time2_arr[1]." minutes";
$time1 = date("H:i:s", strtotime($time1));
}
//Seconds
if(isset($time2_arr[2]) && $time2_arr[2] != ""){
$time1 = $time1." +".$time2_arr[2]." seconds";
$time1 = date("H:i:s", strtotime($time1));
}
return date("H:i:s", strtotime($time1));
}
You could use the PHP 5.3 DateInterval:
$timeInterval = DateInterval::createFromDateString( '15 hours + 20 minutes' );
$timeInterval2 = DateInterval::createFromDateString( '30 minutes' );
foreach( str_split( 'ymdhis' ) as $prop )
{
$timeInterval->$prop += $timeInterval2->$prop;
}
var_dump( $timeInterval->format( '%H:%i:%s' ) );
(How to add to DateInterval objects was explained here: How we can add two date intervals in PHP)
As far as I can tell, Sammaye's answer did't work out for me.
I needed to start the time I wanted to add with the start of the UNIX timestamp. This way, strtotime returns the seconds that need to be added to the first time.
$time1 = "15:20:00";
$time2 = "1970-01-01 00:30:00";
$time = strtotime($time1) + (strtotime($time2) + 3600);
echo $time . "<br />";
echo date("H:i:s", $time);
Be sure to consult the mystic docs http://us1.php.net/strtotime for additional things you can input into your functions :)
$today = time();
$tommorrow = strtotime("+1 days", $today);
$day_after_tomorrow = strtotime("+1 days", $tomorrow);
Code:
$time1 = '15:20:00';
$time2 = '00:30:00';
$time = strtotime($time1)+strtotime($time2);
$sumtime = date("H:i:s",$time);
Related
I have 2 variables.
The first -> ("01:10:00")(string);
The second -> ("2021-02-23 16:30:00")(string)
I want to add the two to be like "2021-02-23 17:40:00".
How can I accomplish this with PHP?
The answers was very much appreciated, thanks everyone.
You can do it by first exploding the time to add (first variable), then you finally add the exploded information to the date (second variable) using function strtotime:
<?php
$firstVar = "01:10:00";
list($hours, $minutes, $seconds) = explode(":", $firstVar);
$secondVar = "2021-02-23 16:30:00";
echo date('Y-m-d H:i:s',strtotime('+'. $hours .' hour +'. $minutes .' minutes +'. $seconds .' seconds',strtotime($secondVar)));
?>
You can do this:
<?php
$newtimestamp = strtotime('2021-02-23 16:30:00 + 70 minute');
// OR $newtimestamp = strtotime('2021-02-23 16:30:00 + 1 hour + 10 minute');
echo date('Y-m-d H:i:s', $newtimestamp); // Output: 2021-02-23 17:40:00
Anyway, if you need to convert HH:MM:SS to minutes, you can use the following function:
<?php
function minutes($time) {
$time = explode(':', $time);
return ($time[0]*60) + ($time[1]) + ($time[2]/60);
}
echo minutes('01:10:00'); // Output: 70
So finally you can do:
<?php
$datetime = '2021-02-23 16:30:00';
$add = minutes('01:10:00');
$newtimestamp = strtotime("$datetime + $add minute");
echo date('Y-m-d H:i:s', $newtimestamp);
function minutes($time) {
$time = explode(':', $time);
return ($time[0]*60) + ($time[1]) + ($time[2]/60);
}
A solution with DateTime. The time is converted into seconds and added using the modify method.
$timeArr = explode(':',"01:10:00");
$seconds = ($timeArr[0]*60 + $timeArr[1]) *60 + $timeArr[2];
$dateTime = date_create("2021-02-23 16:30:00")->modify($seconds." Seconds");
echo $dateTime->format("Y-m-d H:i:s");
This becomes even easier with the external class dt. This class has an addTime() method.
$dt = dt::create("2021-02-23 16:30:00")->addTime("01:10:00");
echo $dt->format("Y-m-d H:i:s"); //2021-02-23 17:40: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'));
I am trying to add hh:mm:ss with the date. How can i do it?
I tried with the following but it works when the hour is string, but when adding time is similar to MySQL Date time it is not working.
$new_time = date("Y-m-d H:i:s", strtotime('+5 hours'));
I am trying to get solution for the following:
$timeA= '2015-10-09 13:40:14';
$timeB = '03:05:01'; // '0000-00-00 03:05:01'
OutPut:
$timeA + $timeB = 2015-10-09 16:45:15 ?
How Can I Add this?
Use DateInterval():
$timeA = new DateTime('2015-10-09 13:40:14');
$timeB = new DateInterval('PT3H5M1S'); // '03:05:01';
$timeA->add($timeB);
echo $timeA->format('Y-m-d H:i:s');
You would need to break your time down into the right DateInterval format but that is easily done with explode();
Here's how that might look:
$parts = array_map(function($num) {
return (int) $num;
}, explode(':', '03:05:01'));
$timeA = new DateTime('2015-10-09 13:40:14');
$timeB = new DateInterval(sprintf('PT%uH%uM%uS', $parts[0], $parts[1], $parts[2]));
$timeA->add($timeB);
echo $timeA->format('Y-m-d H:i:s');
Demo
print date('Y-m-d H:i:s',strtotime($timeA." +03 hour +05 minutes +01 seconds"));
Should work also.
So:
$timeA= '2015-10-09 13:40:14';
$timeB = vsprintf(" +%d hours +%d minutes +%d seconds", explode(':', '03:05:01'));
print date('Y-m-d H:i:s',strtotime($timeA.$timeB));
Can be the solution.
You may also convert the time into seconds with this approach from: Convert time in HH:MM:SS format to seconds only?
$time = '03:05:01';
$seconds = strtotime("1970-01-01 $time UTC");
Then you could add the seconds to
$currentTime = '2015-10-10 13:40:14';
$newTime = date("Y-m-d H:i:s", strtotime( $currentTime.'+'.$seconds.' seconds'));
If you prefer to use the DateTime objects offered by #John Conde, here are two ways to convert the time string into the format:
$formattedTime = preg_replace("/(\d{2}):(\d{2}):(\d{2})/","PT$1H$2M$3S","03:05:11");
or, as you read it from the database:
select concat(hour(last_modified),'H',minute(last_modified),'M',second(last_modified),'H') from people;
So a more general code approach would be:
$initial = 'some time';
$interval = 'the interval value';
$initialTime = new DateTime($initial);
$intervalTime = new DateInterval($interval);
$initialTime->add($intervalTime);
echo $initialTime->format('Y-m-d H:i:s');
It's maybe a really simple question but I found a little hard since I am still novice on PHP.
Presumably I have:
$time1 = strtotime("today 15:00:00-05:00");
This is just example, $time1 is dynamic at runtime and can be any value, I would like to create new $time2 which has the value:
$time2 = strtotime("this thursday 15:00:00-05:00");
Please note in here $time1 and $time2 have the same 15:00:00-05:00 and only different the day. So, to sump up, I have two inputs:
$time1 which is dynamic at runtime.
the string this thursday.
How to create the $time2 with the value like above.
Find the difference between "today" and "today 15:00:00-05:00" and add it to "this thursday"
$sometime = "today 15:00:00-05:00";
$time1 = strtotime($sometime);
// now find only the hour part
$time = mktime(0,0,0, date('n', $time1), date('j', $time1), date('Y', $time1));
$time_difference = $time1 - $time;
$time2 = strtotime("this thursday") + $time_difference;
Or even simpler:
$sometime = "today 15:00:00-05:00";
$time1 = strtotime($sometime);
// now find only the hour part
$hour_string = date('h:i:s', $time1);
$time2 = strtotime("this thursday $hour_string");
Wonder why you don't use DateTime object of PHP right from the start, but ok:
$dateTime = new DateTime($time1);
$dateTime->modify('+1 day');
$time2 = $dateTime->getTimestamp();
Where you can change the 1 to any amount of days.
As I understand what you want is to concat the two string "this thursday" and "15:00:00-05:00":
$str1 = "this thursday";
$str2 = "15:00:00-05:00";
$time = strtotime($str1." ".$str2);
You may try this. And you need to specify more if it is not fulfilling the requirement.
$time1 = date("Y-m-d H:i:s");
$time2 = 'this thrusday ';
$time2 .= $time1;
$time2 = strtotime($time2);
//Example data
$current_time = 1318075950;
$unbanned_time = $current_time + strtotime('+1 minute');
if ($unbanned_time > $current_time) {
$th1is = date('Y-m-d H:i:s', $unbanned_time) - date('Y-m-d H:i:s', $current_time);
echo date('Y-m-d H:i:s', $th1is);
I am trying to output how long time it is until the user is unbanned... year months, days, hours, minutes and seconds... But this is giving me some weird results..
You should check manual on how to work with date/time functions.
First of all, instead of
$current_time + strtotime('+1 minute')
use
strtotime('+1 minute', $current_time);
(see manual on strtotime).
Secondly, date function returns a string. Subtracting two strings is not really useful in most cases.
if ($unbanned_time > $current_time) {
$th1is = $unbanned_time - $current_time;
echo $th1is/3600 . ' hours';
}
This will output the remaining time in hours but there are many functions available that will produce better formatting (or you can code one for yourself).
I would recommend to use DateTime
$DateTime = new DateTime();
$unbanned_DateTime = new DateTime();
$unbanned_DateTime = $unbanned_DateTime->modify('+1 minute');
if ( $unbanned_DateTime > $DateTime ) {
$interval = $DateTime->diff($unbanned_DateTime);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$seconds = $interval->format('%s');
}
Instead of using every single value as variable you can use ->format() for one output. As you like.
Remember DateTime->format() needs a timezone setting up in your php.ini or with
date_default_timezone_set('....');
date() returns a string, substracting two strings makes no sense here. You can use basic maths to calculate the remaining time:
<?php
$current_time = time();
$unbanned_time = /* whatever */;
$seconds_diff = $unbanned_time - $current_time();
echo "You're unbanned at " . date("Y-m-d H:i:s", $unbanned_time) . " which is over ";
if ($seconds_diff <= 120) {
echo "$seconds_diff seconds";
} else if ($seconds_diff <= 7200) {
echo floor($seconds_diff / 60) . " minutes";
} else if ($seconds_diff <= 7200 * 24) {
echo floor($seconds_diff / 3600) . " hours";
} else {
echo floor($seconds_diff / 3600 / 24) . " days";
}
?>