HH:MM to seconds - php

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
?>

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

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

Comparing datetimes in php

I am comparing a date with a datetime and I get the result I expect however I also am wondering if there is a better way to display my output and I have a query on my current output also.
Here is a snippet of my current code:
<?php
$todayDate = date('Y-m-d');
$seconds = strtotime($todayDate) - strtotime($dueDate);
$hours = $seconds / 60 / 60;
echo number_format($hours, 2);
?>
in my case $dueDate in my database here is 2017-06-26 09:11:28 so the output is displaying as -57.19. My question, is there is a clean way to strip the - and also add h after the hours and m after the minutes so the output looks like this?
57h 19m
UPDATE
So After tinkering around I have managed to do this:
substr($dateFormat,0,3).'h '.substr($dateFormat,4).'m';
The output now is -57h 19m
I still have this negative character, im not sure if that is actually correct I cannot seem to work it out because the date in my database is a day ahead but it shows a negative value...
Using the DateTime class makes it very simple
$dueDate = '2017-06-26 09:11:28';
$due = DateTime::createFromFormat('Y-m-d H:i:s', $dueDate);
$today = new DateTime();
$diff = $today->diff($due);
echo $diff->format('%hh %im');
Result:
11h 37m
But as you asked about timezones, here is how to add those in as well. And also as you orignial date was in fact some days distant I added a more accurate difference output
$dueDate = '2017-06-25 00:00:00';
$due = DateTime::createFromFormat('Y-m-d H:i:s', $dueDate, new DateTimeZone('Europe/London'));
$today = new DateTime('now', new DateTimeZone('Europe/London'));
$diff = $today->diff($due);
echo $diff->format('%R %hh %im').PHP_EOL;
if ( $diff->invert ) {
echo $diff->format('Overdue by %dd %hh %im');
} else {
echo $diff->format('You have %dd %hh %im till overdue');
}
Results
+ 1h 6m
You have 0d 1h 6m till overdue
You need to keep date integer
$time = time();
after
you can use this every where and evert way
For example
$date1 = time();
$date2 = time();
$comparingdate = $date2 - $date1;
$myFormat = date("T-m-d h:i:s",$comparingdate); // Show how you want
use floor and round functions to get the minutes and hours after convert the date to positive sign using abs function
<?php
$todayDate = date('Y-m-d');
$dueDate = "2017-06-26 09:11:28";
$seconds =abs(strtotime($todayDate) - strtotime($dueDate));
$hours =floor($seconds / 60 / 60);
$minutes= round($seconds / 60 / 60 - $hours,2)*100;
echo "<br>";
echo $hours. " H :";
echo $minutes. " M ";
?>

Setting a time and date and adding to it in PHP

Basically am trying to set a time and a date in PHP then set a time gap which will range between minutes, loop through between a start time and end time echoing something out for each one. Have tried loads of different ways and cant seem to figure a way to set a date and add to it.
This seems the best script I have modified so far:
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
$newendtime = $endtime->format('Y-m-d H:i');
$timedate = new DateTime('2012-01-01 09:00');
while($stamp < $newendtime)
{
$time = new DateTime($timedate);
$time->add(new DateInterval('PT' . $minutes . 'M'));
$timedate = $time->format('Y-m-d H:i');
echo $timedate;
}
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 8:00');
$interval = new DateInterval('PT' . $minutes . 'M');
while($time < $endtime){
$time->add($interval);
echo $time->format('Y-m-d H:i');
}
Do everything in seconds, and use php's time(), date(), and mktime functions.
In UNIX Time, dates are stored as the number of seconds since Jan 1, 1970.
You can render UNIX Timestamps with date().
$time = time(); // gets current time
$endtime = mktime(0,0,0, 1, 31, 2012); // set jan 31 # midnight as end time
$interval = 60 * 5; // 300 seconds = 5 minutes
while($time < $endtime){
$time += $interval;
echo date("M jS Y h:i:s a",$time) . "<br>"; // echos time as Jan 17th, 2012 1:04:56 pm
}
date reference:
http://us3.php.net/manual/en/function.date.php (includes superb date format reference too)
mktime reference: http://us2.php.net/mktime
time() only gets the current time, but just for kicks n' giggles: http://us2.php.net/time
And, it's super easy to store in a database!
This function will let you add date to your existing datetime. This will also preserves HH:MM:SS
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
?>
Usage:
add_date($date,12,0,0);
where $date is your date.

Categories