How to sum hours with existing datetime in PHP? - 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');

Related

PHP subtract unknown time from datetime

So, I'm creating a booking system. When I retrieve this booking from the database, I need to check if the current date and time is closer to the actual booked date and time.
On the admin dashboard, the admins specify how much time earlier the client can make a checkin, let's say for example, 30minutes. But this time can be different. Can be 1hour, 2hours, 10minutes.
When I get the result from the database I get them like this:
$date_schedule = '2021-03-25 15:40:00'; // Can be any date in the future as well;
$time_to_check = '00:30:00'; // Can be '01:05:00', whatever the admins set as time_to_check;
// Expected result
'2021-03-25 15:10:00';
I tried subtracting this but I didn't made it work.. This is what I did.
$current_date = date("Y-m-d H:i:s");
$booking_date = '2021-03-25 15:00:00'; // From database
$time_to_check = '00:30:00'; // From database
$hours = explode(':', $time_to_check);
$data_check = date($booking_date, strtotime('-' . $hours[0] . ' hour -' . $hours[1] . ' minutes'));
But with this, $data_check returns the same value as $booking_date, it's not subtracting the time.
Convert your date to DateTime to make some operations on it :
function changeDate($date, $interval) {
$datetime = new DateTime($date);
$values = explode(':', $interval);
$datetime->modify("-$values[0] hours -$values[1] minutes -$values[2] seconds");
return $datetime->format('Y-m-d H:i:s');
}
$date = changeDate('2021-03-25 15:00:00', '00:30:00');
echo $date; // 2021-03-25 14:30:00
$date = changeDate('2021-03-25 15:00:00', '01:30:00');
echo $date; // 2021-03-25 13:30:00
$date = changeDate('2021-03-25 15:00:00', '02:30:15');
echo $date; // 2021-03-25 12:29:45
You can find documentation here https://www.php.net/manual/en/book.datetime.php
Just convert the timestamp to Unix time, and then subtract 30 minutes in seconds (30 * 60) from the Unix time.
Like this:
$date = '2021-03-25 15:10:00';
$timestamp = strtotime($date);
$timestamp = ($timestamp - (30 * 60));
echo gmdate("Y-m-d H:i:s", $timestamp);
EDIT: If you are in an odd timezone, like me (GMT+0100) add or subtract difference;
$timestamp = (($timestamp - (30 * 60)) + (1 * 60 * 60))

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

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

HH:MM to seconds

I'm using an API function that returns an estimated time of arrival in hh:mm left, ie. 0:31 left until arrival.
What I'm trying to do is add the returned hh:mm to the current time, so the end result is the estimated time of arrival in UTC.
I currently have a very simple script that works as-is, but as the API function is formatted hh:mm and strtotime doesn't seem to recognize adding or subtracting anything but integers, this won't work if in the following script you replace +07 with +hh:mm.
<?php
$time = strtotime("now +07 hours");
print gmdate('H:i T', $time);
?>
So my end outcome should be hh:mm of the ETA in UTC.
A more flexible way:
<?php
function getETA($arrival, $timezone='UTC', $format='H:i T')
{
list($hours,$minutes) = explode(':', $arrival);
$dt = new DateTime('now', new DateTimeZone($timezone));
$di = new DateInterval('PT'.$hours.'H'.$minutes.'M');
$dt->add($di);
return $dt->format($format);
}
?>
Usage:
<?php
echo getETA('07:10');
echo getETA('07:10', 'America/New_York', 'h:i a T');
?>
Example Output:
23:56 UTC
07:56 pm EDT
If you change your strtotime parameter to now +07 hours, +06 minutes you should be able to add them. To get hours and minutes separate, just use explode(':', $returnedString)
$returnedString = '07:06';
$returnedTime = explode(':', $returnedString);
$time = strtotime("now +{$returnedTime[0]} hours, +{$returnedTime[1]} minutes");
// Or this
// $time = strtotime('now +' . $returnedTime[0] . ' hours, +' . $returnedTime[1] . ' minutes');
print gmdate('H:i T', $time);
<?php
$str = "17:26";
$secs = (substr($str, 0, 2) * 3600) + (substr($str, 3, 2) * 60);
echo $secs;
// Output: 62760
?>

Adding days to $Date in PHP

I have a date returned as part of a MySQL query in the form 2010-09-17.
I would like to set the variables $Date2 to $Date5 as follows:
$Date2 = $Date + 1
$Date3 = $Date + 2
etc., so that it returns 2010-09-18, 2010-09-19, etc.
I have tried
date('Y-m-d', strtotime($Date. ' + 1 day'))
but this gives me the date before $Date.
What is the correct way to get my Dates in the format form 'Y-m-d' so that they may be used in another query?
All you have to do is use days instead of day like this:
<?php
$Date = "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));
?>
And it outputs correctly:
2010-09-18
2010-09-19
If you're using PHP 5.3, you can use a DateTime object and its add method:
$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->add(new DateInterval('P1D')); // P1D means a period of 1 day
$Date2 = $date->format('Y-m-d');
Take a look at the DateInterval constructor manual page to see how to construct other periods to add to your date (2 days would be 'P2D', 3 would be 'P3D', and so on).
Without PHP 5.3, you should be able to use strtotime the way you did it (I've tested it and it works in both 5.1.6 and 5.2.10):
$Date1 = '2010-09-17';
$Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day"));
// var_dump($Date2) returns "2010-09-18"
From PHP 5.2 on you can use modify with a DateTime object:
http://php.net/manual/en/datetime.modify.php
$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->modify('+1 day');
$Date2 = $date->format('Y-m-d');
Be careful when adding months... (and to a lesser extent, years)
Here is a small snippet to demonstrate the date modifications:
$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";
You can also use the following format
strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));
You can stack changes this way:
strtotime("+1 day", strtotime("+1 year", strtotime($date)));
Note the difference between this approach and the one in other answers: instead of concatenating the values +1 day and <timestamp>, you can just pass in the timestamp as the second parameter of strtotime.
Here has an easy way to solve this.
<?php
$date = "2015-11-17";
echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>
Output will be:
2015-11-22
Solution has found from here - How to Add Days to Date in PHP
Using a variable for Number of days
$myDate = "2014-01-16";
$nDays = 16;
$newDate = strtotime($myDate . '+ '.$nDays.' days');
echo new Date('d/m/Y', $newDate); //format new date
Here is the simplest solution to your query
$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days
echo date_format($date,"Y-m-d"); //set date format of the result
This works. You can use it for days, months, seconds and reformat the date as you require
public function reformatDate($date, $difference_str, $return_format)
{
return date($return_format, strtotime($date. ' ' . $difference_str));
}
Examples
echo $this->reformatDate('2021-10-8', '+ 15 minutes', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 hour', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 day', 'Y-m-d H:i:s');
To add a certain number of days to a date, use the following function.
function add_days_to_date($date1,$number_of_days){
/*
//$date1 is a string representing a date such as '2021-04-17 14:34:05'
//$date1 =date('Y-m-d H:i:s');
// function date without a secrod argument returns the current datetime as a string in the specified format
*/
$str =' + '. $number_of_days. ' days';
$date2= date('Y-m-d H:i:s', strtotime($date1. $str));
return $date2; //$date2 is a string
}//[end function]
All have to use bellow code:
$nday = time() + ( 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Day: '. date('Y-m-d', $nday) ."\n";
Another option is to convert your date string into a timestamp and then add the appropriate number of seconds to it.
$datetime_string = '2022-05-12 12:56:45';
$days_to_add = 1;
$new_timestamp = strtotime($datetime_string) + ($days_to_add * 60 * 60 * 24);
After which, you can use one of PHP's various date functions to turn the timestamp into a date object or format it into a human-readable string.
$new_datetime_string = date('Y-m-d H:i:s', $new_timestamp);

Categories