I'm trying to display the time x started, the time x finished, and how long x took to complete. I have the start and end displaying correctly, but the following subtraction gives me a bonkers answer.
// to unix timestamps for subtraction
$startTime = strtotime($row['bp_rec_start']);
$endTime = strtotime($row['bp_rec_end']);
$timeTaken = $endTime - $startTime;
//back to date formats
$startTime = date('H:i',$startTime);
$endTime = date('H:i',$endTime);
$timeTaken = date('H:i',$timeTaken);
e.g. ( 01:24 - 01:23 = 07:01)
Thanks
Timestamps are seconds since 1970, each timestamp representing an absolute point in time. So $endTime - $startTime produces some point in time like 1975-04-12 07:01:52. Printing the hour and minute part of that will of course print 07:01. The timestamp itself though is the difference in seconds, so you can do:
echo "Difference: $timeTaken seconds";
You should of course look into DateInterval (look at the 3rd example).
Related
I need to calculate the difference between 2 UTC time values with 7 decimals in PHP 7.3
Can I simply do the following:
val1 = 20200205120415.6513380; //first timestamp
val2 = 20200205120415.6535670; //second timestamp
$diff = $val2 - $val1; //should be difference between the 2 timestamps
The value of the above calculation is 0.002229. If I am doing it correctly is that value in seconds or microseconds and will I be able to convert it into a UNIX epoch timestamp?
I strongly suspect that the above times are not simple numbers; they BCD (binary coded decimal) for 2020-02-05-12:04:15.6513380. You can't do simple math on these, and you'll need to parse them to convert to a unix timestamp.
Depending on your language, it may be easiest to parse these by turning them into strings and taking the first four characters as the year, the next two as the month, etc.
Here is my current solution for completeness.
The values on the right of the . is indeed fractional seconds. So in PHP to get the difference I did the following:
$start = 20200205120415.6513380;
$end = 20200205120415.6535670;
//get value left of . and then create datetime object to later convert to seconds
list($datetime, $usecStart) = explode(".", $start);
$startTime = date_create_from_format("YmdHis", $datetime);
list($datetime, $usecEnd) = explode(".", $end);
$endTime = date_create_from_format("YmdHis", $datetime);
//get timestamp in seconds and add franction or microseconds back
$start = $startTime->getTimestamp().".".$usecStart;
$end = $endTime->getTimestamp().".".$usecEnd;
//get difference in seconds and fraction or microseconds
echo $end - $start;
Here is another way using datetime->diff() function:
$start = new DateTime('2020-02-05T12:04:15.6513380Z');
$end = new DateTime('2020-02-05T12:04:15.6535670Z');
$diff = $start->diff($end);
echo $diff->format('%h:%i:%s.%F');
I have a table which shows the time since a job was raised.
// These are unix epoch times...
$raised = 1360947684;
$now = 1361192598;
$difference = 244914;
$difference needs to exclude any time outside of business hours (ex, 9-5 and weekends).
How could I tackle this?
The thing you have to do are 3 in numbers.
You take your start date and calculate the rest time on this day (if it is a business day)
You take your end date and calulate the time on this day and
you take the days in between and multiply them with your business hours (just those, that are business days)
And with that you are done.
Find a little class attached, which does those things. Be aware that there is no error handling, time zone settings, daylight saving time, ...
input:
start date
end date
output:
difference time in seconds
adjustable constants:
Business hours
Days that are not business days
Very bad idea, but I had no choice because I'm on php 5.2
<?php
date_default_timezone_set('Asia/Seoul');
$start = 1611564957;
$end = 1611670000;
$res = 0;
for($i = $start; $i<$end; $i++){
$h = date("H", $i);
if($h >= 9 && $h < 18){
//echo date("Y-m-d H:i:s", $i) . "<br>";
$res = $res + 1;
}
}
echo $res;
Use DateTime.
Using UNIX time for this is slightly absurd, and you would have to literally remake DateTime.
Look up relative formats where you can specify the hour on the day, e.g.
$date = new DateTime($raised);
$business_start = new DateTime("09:00"); // 9am today
$business_end = new DateTime("17:00"); // 5pm today
The rest is for you to work out.
Oh, and instead of start/end, you could probably use DateInterval with a value of P8H ("period 8 hours")
The problem with using timestamps directly is that you are assigning a context to a counter of seconds. You have to work backwards from the times you want to exclude and work out their timestamps beforehand. You might want to try redesigning your storage of when a job is raised. Maybe set an expiry time for it instead?
I'm using date('H:i:s', (time() - $start['time'])) to displa time that passed since start of the script.
whatever the result of time() - $start['time'] - be it 0, 17 or whatever the date prints out like 02:00:00, 02:00:17 etc.
What may be the reason?
time returns an absolute numeric timestamp, say the numeric value for 2012-06-04 16:35:12. Your start time is a similar numeric, absolute timestamp. Subtracting one from the other will result in a very small number, which is, again, an absolute timestamp. Likely some time around the beginning of 1970. When you format that timestamp using date('H:i:s'), you only display the time portion of a timestamp like 1970-01-01 02:00:00.
Read about what UNIX timestamps actually represent.
The time difference that you're looking for is the result of time() - $start['time'], which is in seconds, which you can't simply format using date(). More along the lines of:
$diff = time() - $start['time'];
echo 'Difference in seconds: ' . $diff;
echo 'Difference in minutes: ' . $diff / 60;
echo 'Difference in hours: ' . $diff / 60 / 60;
seems you have a 2H offset added.
// save current TZ
$current_tz = date_default_timezone_get();
// Use universal time
date_default_timezone_set('UTC');
$t = time();
echo "T:".$t."<br/>";
sleep(2);
echo "T2: ".date('H:i:s', time() - $t );
// return correct TZ
date_default_timezone_set($current_tz);
If i try this code without the date_default_timezone_set('UTC') it gives me expected value + 1H from Summer Time (GMT+1). If you only need the diference between the 2 times you can use UTC for both and you only get the diference OR you can check the current time offset and subtract it.
Hope it helps
I'm a bit stuck with the DateInterval class of PHP. What I really want is the number of seconds elapsed between two DateTime stamps.
$t1 = new DateTime( "20100101T1200" );
$t2 = new DateTime( "20100101T1201" );
// number of seconds between t1 and t2 should be 60
echo "difference in seconds: ".$t1->diff($t2)->format("%s");
Yet all I get is zero. Is the DateInterval class not suited for arithmetic? How can I get the 'exact' number of seconds (or hours, or whatever) between two time stamps?
If you just want the seconds quickly you might aswell use
$diff = abs($t1->getTimestamp() - $t2->getTimestamp());
Your code returns 0, because the actual seconds difference is 0, the difference in your example is 1 minute (1 minute, 0 seconds). If you print the %i format, you will get 1, which is the correct diff of $t1 and $t2.
I am developing a quiz site and there is time for x min to answer the quiz. So when user clicks on start quiz link the starttime (current time at this instant) is recored in session. Also the endtime (start_time+ 30 min) is recorded in session and every time he submits a answer the current time is compared with the quiz end time. Only if the current time is less than end_time the answer should be accepted.
How can I get the currentdatetime?
How can I add x minutes to current this datetime?
How can I compare (<=) datetime ?
I think we should use date time. Is it right?
PHP measures time as seconds since Unix epoch (1st January 1970). This makes it really easy to work with, since everything just a single number.
To get the current time, use: time()
For basic maths like adding 30 minutes, just convert your interval into seconds and add:
time() + 30 * 60 // (30 * 60 ==> 30 minutes)
And since they're just numbers, just do regular old integer comparison:
$oldTime = $_SESSION['startTime'];
$now = time();
if ($now < $oldTime + 30 * 60) {
//expired
}
If you need to do more complicated things like finding the date of "next tuesday" or something, look at strtotime(), but you shouldn't need it in this case.
use php builtin functions to get time:
<?php
$currentTimeStamp = time(); // number of seconds since 1970, returns Integer value
$dateStringForASpecificSecond = date('Y-m-d H:i:s', $currentTimeStamp);
?>
for your application that needs to compare those times, using the timestamp is more appropriate.
<?php
$start = time();
$end = $start + (30 * 60); // 30 minutes
$_SESSION['end_time'] = $end;
?>
in the page where the quiz is submitted:
<?php
$now = time();
if ( $now <= $_SESSION['end_time'] ) {
// ok!
}
?>
Use the time() function to get a UNIX timestamp, which is really just a large integer.
The number returned by time() is the number of seconds since some date (like January 1, 1970), so to add $x minutes to it you do something like (time() + ($x*60)).
Since UNIX timestamps are just numbers, you can compare them with the usual comparison operators for numbers (< <= > >= ==)
time() will give you the current time in seconds since 1/1/1970 (an integer), which looks like it should be good.
To add x minutes, you'd just need to add x*60 to that, and you can compare it like any other two integers.
Source: http://us3.php.net/time
This is an old question but I wanted to provide an answer based on the PHP 5.2 DateTime class which I feel is much easier to use and much more versatile than any previous functions.
So how can i get the currentdatetime?
You can create a new DateTime object like this:
$currentTime = new DateTime();
But at this point, $currentTime is a datetime object and must be converted to a string in order to store it in a database or output it.
$currentTime = $currentTime->format('Y-m-d H:i:s');
echo $currentTime;
Outputs 2014-05-10 21:14:06
How can i add x minutes tocurrent this datetime?
You can add x minutes with the modify method:
$currentTime = new DateTime();
$addedMinutes = $currentTime->modify('+10 minutes');
echo $addedMinutes;
Outputs 2014-05-10 21:24:06
How can i comapare (<=) datetime ?
With the DateTime class, you can not only easily compare datetime objects, you can get the difference between them.
$currentTime = new DateTime('2014-05-10 21:14:06');
$addDays = $currentTime->modify('+10 days');
To compare
if ($currentTime >= $addDays) {
//do something//
}
$diffTime = new DateTime('2014-05-10 21:14:06');
$diff = $addDays->diff($diffTime);
$diff = $diff->format('There are %d days difference.');
echo $diff;
Outputs There are 10 days difference.