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
Related
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.
I need to get different time lengths in minutes from a few timestamps that are:
starttime
endtime
starttime2nd
endtime2nd
Edit: clarification:
Each time is originally stored as a datetime string, like
"2018-02-21T19:45:13+00:00".
I take that and convert it to strtotime("2018-02-21T19:45:13+00:00");
And from that I get a timestamp : 1519242313
It doesn't seem that I can use plus or minus operators to add or subtract timestamps, like:
$length = ($endtime2nd - $starttime2nd) + ($endtime - $starttime)
Am I required to instantiate DateTime and use the "->diff" method to get a time interval?
I could get one time interval by doing this:
$date1 = new DateTime();
$date2 = new DateTime();
$starttime= $date1->setTimestamp($starttime);
$endtime= $date2->setTimestamp($endtime);
$length = $endtime->diff($starttime);
Does this mean that I need to instantiate four DateTimes to get the total length, and set four timestamps, then get the "->diff" for the two time intervals, and then add them using the "->add" method of DateTime method?
I would just like to know if there is a simpler method?
I don't think you need to instantiate DateTime and use the "->diff" method, because you already have timestamp (as i can see you are using setTimestamp)
<?php
$length = ($endtime2nd - $starttime2nd) + ($endtime - $starttime);
echo round(abs($length / 60), 2). " minute";
?>
You can get the total minuts like this.
$min = $length->d * 24 * 60;
$min = $min + $length->h * 60;
$min = $min + $length->m;
I'm just want to check if my way is correct or not. I want to calculate the remaining time for an event.
There are 3 component for it.
The start datetime (in mysql datetime), which is retrieved from mysql.
The duration (minutes in integer), which is also retrieved from mysql.
The current datetime, which is retrieved from php function now().
To count:
The remaining time (in time hh:mm:ss), which is from formula (start + duration) - now
My propose code is:
$row = data->fetch_assoc();
$start = $row["start_time"]; // e.g: "2015-06-19 09:37:16"
$duration = $row["duration"]; // e.g: 60 (minutes)
$now = time(); // e.g: 1434648994
$start_dt = strtotime ($start);
$remaining = ($start_dt + $duration * 60) - $now;
echo "Remaining time: ".$remaining. " seconds."
Is this correct?
Your code now calculates time until the end of the event.
And if $start_dt is lower then $now you get negative value.
i use ths method to find the difference between two timestamp and get the number of seconds between those two times, and i refresh the information with jquery like a counter.
$diff = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
$time = intval(date('s', $diff));
echo $time;
When the difference is more than 60 seconds, the $time comes back to 0, like a reset.
i would like to display 1 min XX s for example
The s flag for date() will never return a value greater than 59 as it only represents the current number of seconds of a given time which can never be more than 59 before rolling over into a new minute.
If you want the total number of seconds you can actually remove your second line of code as the difference between two Unix Timestamps is always in seconds:
$time = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
echo $time;
If you want to display this as minutes and seconds you can use DateTime() which offers better tools for this:
$now = new DateTime();
$then = new DateTime('2014-06-25 14:50:03');
$diff = $now->diff($then);
echo $diff->format('%i minutes %s seconds');
format the date
$diff = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
$time = date('i:s', $diff);
echo $time;
Pass time like 1 & now 2
function diffrencePassTimeAction($DataTime){
$im = $DataTime - strtotime("now");
return $im;
}
Future time like 2 & now 1
function diffrenceFuturTimeAction($DataTime){
$im = strtotime("now") - $DataTime;
return $im;
}
this function delete (-less)
function diffrencePassTimeAction($DataTime){
if ($DataTime > 0)
return $DataTime - strtotime("now");
else
return strtotime("now"); // OR return 0;
}
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