PHP Adding minutes to Time value - php

How can I add time to a digit time value,
currently my code looks like this:
$time = strtotime('00:00:00');
$addTime = strtotime('+5 minutes', $time);
$addTime = date('h:i:s', $addTime);
If I echo $addTime I get this value:
1472680800147268110012:05:00
which is obviously wrong.
It should look like this:
00:05:00

Replace $addTime = date('h:i:s', $addTime); with $addTime = date('H:i:s', $addTime);
According to manual http://php.net/manual/en/function.date.php
H 24-hour format of an hour with leading zeros 00 through 23

It should be like this:
<?php
$addMinutes = 16;
$yourTime = new DateTime('08:02:00');
$yourTime->add(new DateInterval('PT' . $addMinutes . 'M'));
$result = $yourTime->format('H:i:s');
var_dump($result);
?>
Demo

Why don't simply write:
$time = strtotime('00:00:00');
$addTime = date('H:i:s', $time+5*60);

Related

PhP date time addition

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

How to display time in PHP by date() function

I get the value 9.0 from a CSV file that I would like to print as the time 09:00:00
If i try
<?php
$time = 9.01;
echo date('H:i:s', strtotime($time));
It displays 09:01:00.
But if I try
<?php
$time = 9;
echo date('H:i:s', strtotime($time)); or echo date('H:i:s', strtotime(9.00));
It displays 01:00:00.
I want to get time 09:00:00.
Please try this
$time = 9;
echo date( 'H:i:s', strtotime( number_format($time, 2)));
This is how to fill a date variable with any value you need:
<?php
$d=mktime(9, 0, 0);
echo "Created date is " . date("h:i:s", $d);
?>
See the documentation of mktime
It appears the main issue is the import CSV has a malformed date. Assuming you cannot change it and that the value is {hours}.{minutes}. Minutes not being a fraction but a value between 0 - 60. Otherwise, this will need adjusting to convert the fraction of an hour into minutes.
I'm using the DateTime class to achieve this.
$value = 9.1;
if (is_float($value)) {
$hour = (int)$value;
$minute = number_format(($value - floor($value)) * 100);
$date = new DateTime();
$date->setTime($hour, $minute);
} else {
$date = new DateTime($value);
}
$formattedTime = $date->format('H:i');
echo $formattedTime . "\n";
For 12 hours Formate
echo date("h:i:s a");
For 24 hours Formate
echo date("H:i:s");

How to sum hours with existing datetime in PHP?

I have two fields which store data like 2018-03-26 11:20:35 and 02:25:10(2 hours 25 minutes and 10 seconds) first data is date and time. second one is only time. I want to sum it and finally my result should 2018-03-26 13:45:45
How to do that in php code?
I have tried this way:
<?php
$date = '2018-03-26 11:20:35';
//echo $date;
//echo "<br>";
$hours = '02:25:10'; /* this data dynamic */
$sumTime = strtotime($date) + strtotime($hours);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Output:
Warning: date() expects parameter 2 to be integer, float given in C:\my-project-path\test.php on line 7
Here's a simple solution, some checks are skipped:
// convert your date to DateTime object
$date = '2018-03-26 11:20:35';
$dt = new DateTime($date);
// convert your period to DateInterval
$hours = '02:25:10'; /* this data dynamic */
$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');
// Add interval to date
$dt->add($interval);
// Format date as you need
echo $dt->format('Y-m-d H:i:s');
You could create a duration in seconds by comparing today at "00:00:00" and today at $hours. Actually, strtotime($hours) returns the timestamp of today at $hours, so, the addition of the two timestamp don't give the expected result.
If $hours is lesser than 24 hours, you could use:
$date = '2018-03-26 11:20:35';
$hours = '02:25:10';
$d0 = strtotime(date('Y-m-d 00:00:00'));
$d1 = strtotime(date('Y-m-d ').$hours);
$sumTime = strtotime($date) + ($d1 - $d0);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Outputs:
2018-03-26 13:45:45
You should check DateTime::add:
http://php.net/manual/en/datetime.add.php
http://php.net/manual/en/datetime.examples-arithmetic.php
Example:
<?php
// Convert h:m:s format to PThHmMsS format
sscanf('02:25:10', '%d:%d:%d', $hour, $minute, $second);
$intervalSpec = sprintf('PT%dH%dM%dS', $hour, $minute, $second);
$datetime = new DateTimeImmutable('2018-03-26 11:20:35');
$newDatetime = $datetime->add (new DateInterval($intervalSpec));
echo $newDatetime->format(DateTime::W3C);
It could be done with some simple string manipulation:
$dt = new DateTime("$date UTC");
$modify = preg_replace('/:/', ' hours ', $hours, 1);
$modify = preg_replace('/:/', ' minutes ', $modify, 1);
$modify .= ' seconds';
$dt->modify($modify);
demo
If you have MySQL as your data storage, you could do:
DATE_ADD(field1, INTERVAL field2 HOUR_SECOND)
demo
you can do something like:
$hour = $hours->format('H'); //This way you get a string which contains the hours
$date->modify('+'.$hour.' hour'); //you modify your date adding the hours
I'm assuming you only need the hours, and not minutes and seconds
EDIT:
you can do like that using regexp
$date = new \DateTime('2018-03-26 11:20:35');
$hours ='02:25:10';
preg_match("/^([0-9].*):([0-9].*):([0-9].*)/",$hours,$matches);
$date->modify('+'.$matches[1].' hour');
$date->modify('+'.$matches[2].' minute');
echo $date->modify('+'.$matches[3].' second')->format('Y-m-d H:i:s');

PHP Minus time in Format

I want to keep the H:i:s format so 10:52:20 however when I try:
$timeleft = strtotime($time1)-strtotime($time2);
I get something like 4521
I would like the result to retain the format. Is there a way to do this?
Yeah, what you get is unix timestamp which is in seconds. You can use date function to get required format like this:
$timestr_formated = date("H:i:s", $timeleft);
print($timestr_formated);
You can use DateTime::diff.
$time1 = new DateTime('2017-05-01 12:00:00');
$time2 = new DateTime('2017-05-01 11:25:30');
$timeleft = $time1->diff($time2);
echo $timeleft->format('%H:%i:%s'); // output: 00:34:30
In case you want to allow more than 24 hours.
$time1 = new DateTime('2017-05-02 12:00:00');
$time2 = new DateTime('2017-04-02 11:25:30');
$timeleft = $time1->diff($time2);
echo str_pad($timeleft->format('%a') * 24 + $timeleft->format('%h'), 2, "0") .
$timeleft->format(':%i:%s'); // output: 720:34:30
You can use date function by below format:
$timeleft = date('H:i:s', strtotime($time1)-strtotime($time2));

add hours:min:sec to date in PHP

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');

Categories