add hours:min:sec to date in PHP - 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');

Related

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

Get date, hour and minute as separate variables from a datetimestamp in PHP

In PHP if I have a variable ($getTimeStamp) that follows the format 0000-00-00 00:00:00 (i.e. 2013-09-26 13:06:00).
What is the easiest way to get the date ($getDate), hour ($getHour) and minute ($getMinute) as separate variables?
The easiest way is to use PHP DateTime class
$getTimeStamp = '2013-09-26 13:06:00';
$date = new \DateTime($getTimeStamp);
$dateString = $date->format('Y-m-d');
$hourString = $date->format('H');
$minuteString = $date->format('i');
It's not timestamp ;) Check what time() function returns, that's how timestamp looks like.
You can use something like that:
$time = strtotime($getTimeStamp);
$getDate = date('Y-m-d', $time);
$getHour = date('H', $time);
$getMinute = date('i', $time);
You can simply achieve this using -
$time = strtotime($getTimeStamp);
$getDate = date('Y-m-d', $time);
$getHour = date('H', $time);
$getMinute = date('i', $time);
Have a look at time() and date().
Well, since all you want is really to parse some text this would be the shortest way:
list($date, $hour, $minute) = preg_split('/[ :]/', $getTimeStamp);
There is no real reason to involve the date/time classes if you are not manipulating dates or calculating timestamps.
Live example.
Just one answer using the DateTime class
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $getTimeStamp);
$date = $dt->format('Y-m-d ');
$hour = $dt->format('H');
$minutes = $dt->format('i');

Adding dates from SQL in PHP (types Datetime + Time)

I'd like to add 2 values from MySQL database in an php app. One is stored as a Datetime type, the other one as Time.
$datetime; // "2013-02-08 14:00:00"
$time; // "01:00:00"
I'd like to add 1 hour to $datetime, this doesn't give me the correct result:
$newdatetime = strtotime($datetime) + strtotime($time);
echo date('Y-m-d H:i:s', $newdatetime); // "1920-02-11 08:31:44"
How can I do this correctly?
$dt = new DateTime("2013-02-08 14:00:00");
$dt->modify('+1 hour');
echo $dt->format('Y-m-d H:i:s');
See it in action
$datetime = DateTime::createFromFormat('Y-m-d H:i:s', $datetime);
// extract H, M, S
$time = sscanf($time, '%d:%d:%d');
// build date interval string
$time = vsprintf('PT%dH%dM%dS', $time);
// add it to your date
$datetime->add(new DateInterval($time));
print $datetime->format('Y-m-d H:i:s');
But if $time is always one hour, John Conde's solution would be a better choice :P
Hmm I've dealt with it this way:
$datetime = "2013-02-08 14:00:00";
$time = "01:00:00"; //not always 1 hour, value from db
$t = explode(":",$time); // array(01,00,00)
$hour = mktime($t['0'],$t['1'],$t['2'],1,1,1970); // 3600
$newdatetime = strtotime($datetime) + $hour;
echo date("Y-m-d H:i:s",$added); // "2013-02-08 15:00:00"
Not the most elegant way, but works! As I'm looking now it's simmilar to One Trick Pony's solution, only not objective.

PHP: add seconds to a date

I have $adate; which contains:
Tue Jan 4 07:59:59 2011
I want to add to this date the following:
$duration=674165; // in seconds
Once the seconds are added I need the result back into date format.
I don't know what I'm doing, but I am getting odd results.
Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.
If you are using php 5.3+ you can use a new way to do it.
<?php
$date = new DateTime();
echo $date->getTimestamp(). "<br>";
$date->add(new DateInterval('PT674165S')); // adds 674165 secs
echo $date->getTimestamp();
?>
Just use some nice PHP date/time functions:
$adate="Tue Jan 4 07:59:59 2011";
$duration=674165;
$dateinsec=strtotime($adate);
$newdate=$dateinsec+$duration;
echo date('D M H:i:s Y',$newdate);
Given the fact that $adate is a timestamp (if that's the case), you could do something like this:
$duration = 674165;
$result_date = strtotime(sprintf('+%d seconds', $duration), $adate);
echo date('Y-m-d H:i:s', $result_date);
// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));
Do this:
$seconds = 1;
$date_now = "2016-06-02 00:00:00";
echo date("Y-m-d H:i:s", (strtotime(date($date_now)) + $seconds));
$current_time_zone = 150;
date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s"))+$current_time_zone);
I made this example for a timezone, but if you change some parts it may help you out:
$seconds_to_add = 30;
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Europe/London'));
$time2 = $time->format("Y/m/d G:i:s");
$time->add(new DateInterval('PT' . $seconds_to_add . 'S'));
$timestamp = $time->format("Y/m/d G:i:s");
echo $timestamp;
echo '========';
echo $time2;
Result:
2018/06/17 3:16:23========2018/06/17 3:15:53
It would be easier with DateTime::modify
(new DateTime($str))->modify("+$duration seconds"); //$str is the date in string
I have trouble with strtotime() to resolve my problem of add dynamic data/time value in the current time
This was my solution:
$expires = 3600; //my dynamic time variable (static representation here)
$date = date_create(date('Y-m-d H:i:s')); //create a date/time variable (with the specified format - create your format, see (1))
echo date_format($date, 'Y-m-d H:i:s')."<br/>"; //shows the date/time variable without add seconds/time
date_add($date, date_interval_create_from_date_string($expires.' seconds')); //add dynamic quantity of seconds to data/time variable
echo date_format($date, 'Y-m-d H:i:s'); //shows the new data/time value
font: https://secure.php.net/manual/en/datetime.add.php (consult Object Oriented style too, the Elzo Valugi solution)
(1) https://secure.php.net/manual/en/function.date.php

Categories