I need add extra 24 hours to default time PHP - php

I need add extra 24 hours to my default time and store in database like start time is = default time, end time is = start time + 24 hours.
I already try this way. hear is the code.
<?php
date_default_timezone_set("Asia/Colombo");
$time = date("H:i:s");
$validtime = '24:00:00';
$endtime = strtotime($time + $validtime);
echo date('H:i:s', $endtime);
$bookname= $_GET['id'];
$link=mysqli_query($conn, "update reserve_table set username='$_SESSION[username]', bookname='$bookname', reservetime='$time', endtime='$endtime'");
?>
and pop up this error
Notice: A non well formed numeric value encountered in
/opt/lampp/htdocs/Lowa/student/reserve.php on line 33
Notice: A non well formed numeric value encountered in
/opt/lampp/htdocs/Lowa/student/reserve.php on line 33 05:30:00

PHP cannot add dates in the '24:00:00' format. This is a strings, not a number or "time" thingy. You can add time when it is expressed as a number in seconds. So this will work:
// get time in seconds as an integer
$time = time();
// show it in seconds and formated
echo "In seconds: $time formated: " . date("Y-m-d H:i:s", $time);
// add a day
echo "<br>Add a day.<br>";
$time += 24 * 60 * 60;
// show it in seconds and formated
echo "In seconds: $time formated: " . date("Y-m-d H:i:s", $time);
time() return the current time in seconds. We then add a whole day worth of seconds and convert it to the format you need.

Related

How to Add Time with Duration dynamically in PHP?

I am fetching start date and total duration from database. how to add time and duration to calculate total time in php
Below is the data iam getting dynamically.
<?php
$currenttime= date("H:i");
$starttime=$entrance->start_time;
$duration=$entrance->duration;
?>
<?php
$finalstarttime= $starttime + $duration ;
?>
How to get above result.
Time format is H:i
Using the class DateTime it would be something like this:
<?php
$starttime = "16:15";
$duration= "10";
$finalstarttime = (DateTime::createFromFormat("H:i", $starttime))->add(new DateInterval("PT".$duration."M"));
echo $finalstarttime->format("H:i"); // 16:25
where
DateTime::createFromFormat("H:i", $starttime)
creates a DateTime object of the given time-string,
new DateInterval("PT".$duration."M")
creates a DateInterval (in Minutes)
which is added to the starttime via DateTime::add()
$stamp = mktime(16, 15);
$stamp += 60 * 10;
echo date("H:i", $stamp);
OR
$stamp = strtotime("16:15");
$stamp += 60 * 10;
echo date("H:i", $stamp);
Output: 16:25
Use mktime or strtotime to convert your hour and minute to timestamp (which is in seconds), convert your duration in second 10 min * 60 add both of them.
Now get back the final time using date function

PHP: Wrong Time Calculation

I am working on a project and writing a function to add two different times. The times are stored in database as a string.
I'm:
Pulling value from db
converting it into time using strtotime
adding times using date function
Here is my code:
$time_1 = '1:00';
$time_2 = '0:05';
//should be 1:05, whereas it prints 04:05
echo date("H:i", strtotime($time_1) + strtotime($time_2));
Please tell me, what is wrong with above code and how it can be fixed?
Thanks
Your problem is because strtotime returns the number of seconds since the Unix Epoch (Jan 1 1970). So what you are getting is not values of 60 and 5, but something more like 1537570800 and 1537567500. When you add those two values together, you end up with a date far in the future, with what looks effectively like a random time. To compensate for this, you need to subtract the value of strtotime at the start of the day to make the second time a relative time e.g.:
echo date("H:i", strtotime($time_1) + strtotime($time_2) - strtotime('00:00'));
Output:
01:05
Update
Since it turns out that the sum of the two times can exceed 24 hours, the above code will not work (the maximum time it will display is 23:59 before rolling over to 00:00. So it is necessary to convert both times to a relative number of minutes to the start of the day, add them and then display as hours and minutes:
$time_1 = '12:00';
$time_2 = '14:30';
$time_sum = (strtotime($time_1) + strtotime($time_2) - 2 * strtotime('00:00')) / 60;
printf('%02d:%02d', intdiv($time_sum, 60), $time_sum % 60);
Output:
26:30
Use DateTime::createFromFormat function, and taking ideas from Adding two DateTime objects in php
$time_1 = '1:00';
$time_2 = '0:05';
$t1 = DateTime::createFromFormat('G:i', $time_1);
$t2 = DateTime::createFromFormat('G:i', $time_2);
$interval1 = $t1->diff(new DateTime('00:00:00')) ;
$interval2 = $t2->diff(new DateTime('00:00:00')) ;
$e = new DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
$total = $f->diff($e)->format("%H:%I:%S");
Additional Details:
G and H 24-hour format of an hour with or without leading zeros
i Minutes with leading zeros 00 to 59

How to find at what time activity finished?

I have activity start time and and total hour i just want to find the end time of that activity i mean time when activity finished ?
for example I start my activity
for
$hour = 24:60:08 // 24 hour 60 min 8 min total hour
$starttime = 13:09 // using 24 hour format it 01:09
//means activity start at = 13:09
$endtime = ?
I want to find out the the time finished time of an activity
Thanks
You can with adding to time exploded hour like following:
$hour = '24:60:08';
$starttime = '13:09';
$times = explode(':', $hour);
$timestamp = strtotime($starttime) + ($times[0] * 3600 + $times[1] * 60 + $times[2]);
$endtime = date('H:i', $timestamp);
echo $endtime; // 14:09
Explain:
24 = 24(hours) * 60(mins) * 60(secs)
60 = 60(mins) * 60(secs)
08 = 8(sec)
It appears like you have a start time of an activity and then a duration of how long it ran and you want to compute what's the end time. Your question becomes unclear by your use of non descriptive variable names nor any comments. You can do
<?php
$duration = "25:00:08";
$starttime = "13:09";
list($hours,$minutes,$seconds) = explode(":",$duration);
$totalTime = $seconds+($minutes*60)+($hours*3600);
$endTime = date("h:i",strtotime($starttime)+$totalTime);
echo $endTime;
?>
Sidenote: 24:60:08, 60 minutes is nothing. That's 25 hours 0 minutes and 8 seconds
If you want to get the time elapsed to process something, let's say to execute a function, you can easily do it with PHP microtime.
Assume you want to find time elapsed to execute function test, here how you do this.
public function test()
{
$time_start = microtime(true);
/*
Your code
goes here
*/
$time_end = microtime(true);
$execution_time = (($time_end - $time_start) / 60) * 60;
echo $execution_time; //This will show you the execution time in seconds.
}
If you want, you can add this seconds to any previous time stamp you saved, in order to get the execution terminated time in hh:mm:ss format. Hope this helps.
Cheers!
I am unable to understand exactly what you are looking for
<?php
$hour = "24:60:08"; // 24 hour 60 min 8 min total hour
$starttime = "13:09";
$hourArray=explode(":", $hour);
$starttimeArray=explode(":", $starttime);
$endtimearray=array();
for ($i=0;$i<3;$i++){
//Verifyng time is set else making it zero
if (!isset($hourArray[$i]))
$hourArray[$i]=0;
if (!isset($starttimeArray[$i]))
$starttimeArray[$i]=0;
$endtimearray[$i]=$hourArray[$i]-$starttimeArray[$i];
}
echo $endtimearray[0];
for ($i=1;$i<3;$i++)
echo ":$endtimearray[$i]";
Hopefully This is what you are looking for.

Multiple hour by a number

I have something like that for example: 01:06:22 this represents 1hour, 6minutes and 22seconds. I want to take that, and multiple it by 6 and add it to some other hour such as 04:23 which is 4AM and 23Minutes not 4hours and 23 minutes.
Basically, as a result I expect that:
01:06:22
* 6 = 6hours 38minutes canceling the remaining seconds which are 12 in this case
Now, I want to take that and append it to other hour, 04:23 in this case, so the result would be:
11:01.
I have no clue how to start and do it, unfortunately.
Any help is appriciated!
Clarifications
The time that I have to multiple by 6 will never exceed 2 hours.
All the times are in the same format.
With DateTime it is simple:
$time = '01:06:22';
$dateSeconds = new DateTime("1970-01-01 $time UTC");
$seconds = $dateSeconds->getTimestamp() * 6;
$interval = new DateInterval('PT'.$seconds.'S');
$date = new DateTime('1970-01-01 04:23:00 UTC');
$date->add($interval);
echo $date->format('H:i:s');
Other solution with strtotime and gmdate. (Similar to Suresh but working):
$date = strtotime('1970-01-01 01:06:22 UTC');
$add = strtotime('1970-01-01 04:23:00 UTC');
$date = (($date*6)+$add);
echo gmdate('H:i:s', $date);
This is a solution if you want to implement it yourself.
The thing about timecode is that it can become really heavy with the if the if conditions etc if you don't do it right.
The best Way I thought of to deal with this is to convert everything to second.
so 01:06:22 would become:
numberOfSecond = 22 + 06 * 60 + 01 * 60 * 60
How to get the 22, 06 etc from the String? You can use Regex.
What you will need:
a function to extract the different values (hours, minute, second)
a function to convert the timecode into second
a function to convert back into timecode
the functions to multiply, add etc...
You might want to create a class for it.
You can try like this:
$date = strtotime('01:06:22');
$add = strtotime('00:04:23');
$date = ($date*6)+$add;
echo date('H:i:s', $date);
Note: Code is not tested.
First of all you want to multiply a time span by a factor. The easiest way to do this is to convert the span to seconds and do a straight multiply:
$date =DateTime::createFromFormat('!H:i:s', '01:06:22', new DateTimeZone('UTC'));
$seconds = $date->getTimestamp();
This code works by pretending that the time is a moment during the Unix epoch start so that it can then get the number of seconds elapsed since the epoch (the timestamp). That number is equal to the duration of the time span in seconds. However, it is vitally important that the input is interpreted as UTC time and not as something in your local time zone.
An equivalent way of doing things (as long as the input is in the correct format) which is lower-tech but perhaps less prone to bugs would be
list($h, $m, $s) = explode(':', '01:06:22');
$seconds = $h * 3600 + $m * 60 + $s;
Now the multiplication:
$seconds = $seconds * 6;
If you want to only keep whole minutes from the time you can do so at this stage:
$seconds = $seconds - $seconds % 60;
The final step of adding the result to a given "time" is not clearly specified yet -- does the reference time contain date information? What happens if adding to it goes over 24 hours?
Self explanatory :
$initialTime = '01:06:22';
$timeToAdd = '04:23';
$initialTimeExploded = explode( ':' ,$initialTime );
$initialTimeInMintues = ( $initialTimeExploded[0] * 60 ) + $initialTimeExploded[1];
$initialTimeInMintuesMultipliedBySix = $initialTimeInMintues * 6;
$timeToAddExploded = explode( ':' ,$timeToAdd );
$timeToAddExplodedInMintues = ( $timeToAddExploded[0] * 60 ) + $timeToAddExploded[1];
$newTimeInMinutes = $initialTimeInMintuesMultipliedBySix + $timeToAddExplodedInMintues;
$newTime = floor( $newTimeInMinutes / 60 ) .':' .($newTimeInMinutes % 60);
echo $newTime;
Result :
10:59

Why do I get unexpected hour when substracting two times

I have this simple function to subtract time: the input values are:
$current = '23:48:32';
$arrival = '23:41:48';
$time = date( "H:i:s", strtotime($current) - strtotime($arrival));
$waitingTime = $time; // 21:06:44
Looks like the diff for the minutes is correct, I am not sure why I am getting the 21 in front of the minutes. It should be 00:06:44.
Any help is appreciated.
Thank you.
try using gmdate()
$time = gmdate( "H:i:s", strtotime($current) - strtotime($arrival));
You can't expect this code to give you an interval.
the strtotime($current) - strtotime($arrival) line calculates a interval in seconds but when you pass it to date it assumes your speaking of an interval since epoch. so you get timezone translated value for $time; you must have gotten 9 because your probably behind UTC
use strtotime($current) - strtotime($arrival) / 3600 for hours and remainder divide by 60 for minutes. and then seconds
That's why PHP has DateTime & DateIntervals:
<?php
header('Content-Type: text/plain; charset=utf-8');
$current = '23:48:32';
$arrival = '23:41:48';
$current = DateTime::createFromFormat('H:i:s', $current);
$arrival = DateTime::createFromFormat('H:i:s', $arrival);
$diff = $current->diff($arrival);
unset($current, $arrival);
echo $diff->format('%H:%I:%S');
?>
Output:
00:06:44
This code echo 00:06:44!
$current='23:48:32';
$arrival='23:41:48';
$time = date( "H:i:s", strtotime($current) - strtotime($arrival));
echo $time;//00:06:44
What exactly is your problem?

Categories