How can subtract seconds from a time on seconds? - php

From a time like:
$time_on_seconds = 18000;
It is equal to 5 hours.
Now for subtract seconds Im using this code:
$new_time_on_seconds = date("H:i", strtotime($time_on_seconds) - 60);
It return me 23:59 when this should return me 4:59

Just remove strtotime.
Strtotime does what the name says it takes a str (string) and makes it time (seconds) so using that on a already number won't work.
$time_on_seconds = 18000;
echo $new_time_on_seconds = date("H:i", $time_on_seconds - 60);
But keep in mind date() is timezone aware so you may end up with a wrong result depending on your timezone.
Set the timezone to UTC and you should get the correct result.

Related

PHP Time Since Function Bug

i am writing a time since function to return the time since a given mysql datetime. When taking the $oldtime from current time() it is returning a negative int when i need a positive int. I have written similar functions before in other languages but i have become blind to this problem, so any help would be much appreciated.
function timeSince($time){
$today = date("Y");
$oldtime = strtotime($time);
$time = time() - $oldtime;
$tokens = array (
3600 => 'h',
60 => 'm',
1 => 's'
);
if($time >= 86400){
}
}
echo timeSince('2016-02-25 14:35:00');
it could be much more convenient if you use PHP's DateTime and DateInterval classes and their methods:
function timeSince($datetime) {
$now = strtotime("now");
$then = strtotime($datetime);
$dt_now = new DateTime("#" . $now);
$dt_then = new DateTime("#" . $then);
//DateTime's diff method returns a DateInterval object which got a format method:
return $dt_now->diff($dt_then)->format('%a days, %h hours, %i minutes and %s seconds');
}
some test cases:
//my local date & time is around "2016-02-25 19:49:00" when testing
echo '<pre>';
echo timeSince('2016-02-25 19:30:00');
//0 days, 0 hours, 19 minutes and 11 seconds
echo PHP_EOL;
echo timeSince('2013-11-02 15:43:12');
//845 days, 4 hours, 4 minutes and 3 seconds
echo PHP_EOL;
echo timeSince('2017-01-31 00:22:45');
//340 days, 4 hours, 35 minutes and 30 seconds
echo PHP_EOL;
echo timeSince('1950-05-14 07:10:05');
//24028 days, 12 hours, 37 minutes and 10 seconds
echo PHP_EOL;
code partially based on this answer: https://stackoverflow.com/a/19680778/3391783
strtotime uses timezone in your PHP settings. Depending on timezone set, it might convert to the time that is yet to happen. For example, on my ukrainian server, strtotime('2016-02-25 14:35:00') converts to 1456403700, on a server in another timezone (US/Pacific) it converts to 1456439700.
Quote from PHP docs:
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
Each parameter of this function uses the default time zone unless a time zone is specified in that parameter. Be careful not to use different time zones in each parameter unless that is intended. See date_default_timezone_get() on the various ways to define the default time zone.
You can add UTC/GMT offset to your datetime (1st param), for example strtotime('2016-02-25 14:35:00 +0800') or ('2016-02-25 14:35:00 GMT+08:00') will convert to 1456382100
In your example, $oldtime must be smaller value than current time().
So, if you want to count time between larger value, simply reverse your equation:
This line:
$time = time() - $oldtime;
Becomes:
$time = $oldtime - time();

How to compare current time with old time in PHP

I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
$lastUpdatedField = $rows_fetch['lastUpdatedTime'];
$lastUpdatedDate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two
$interval = $nowDate->diff($lastUpdatedDate);
echo $interval->h;
DateDiff: http://www.php.net/manual/en/datetime.diff.php
DateInterval: http://www.php.net/manual/en/class.dateinterval.php
Had The same problem earlier its actually quit simple
heres the piece where you declare your variables
$lastUpdateddate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
Then you have to convert them to second - format so that you can do math with them
To do that use strtotime
$Diff = strtotime($lastUpdatedDate) - strtotime($nowDate);
Then just check to see if the difference in time is more then 60 minutes,
So devide by 60 seconds to get minutes and by 60 to get hours
if ($diff/60/60 <= 1){
//do your thing here
{
First convert the current time and old time to one unit like Unix timestamp passing it through strtotime(). Then differentiate both the timestamp to get the difference between two times.
$difftime = strtotime(date('Y-m-d H:i:s')) - strtotime($rows_fetch['lastUpdatedTime']);
Then convert the difference to days as follows :
$days=$difftime/24*60*60;
Once you get the days you can get the minutes from it as below to compare to meet your need.
$timediff = $days * 24 * 60;

PHP's date usage results in 2 hours error

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

How to obtain, increment, and compare datetime in PHP?

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.

Determining elapsed time

I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:
8:30 to 10:00 would be 1:30
A solution might be to use strtotime to convert your dates/times to timestamps :
$first_str = '8:30';
$first_ts = strtotime($first_str);
$second_str = '10:00';
$second_ts = strtotime($second_str);
And, then, do the difference :
$difference_seconds = abs($second_ts - $first_ts);
And get the result in minutes or hours :
$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);
You'll get :
int 90
float 1.5
What you now have to find out is how to display that ;-)
(edit after thinking a bit more)
A possibility to display the difference might be using the date function ; something like this should do :
date_default_timezone_set('UTC');
$date = date('H:i', $difference_seconds);
var_dump($date);
And I'm getting :
string '01:30' (length=5)
Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...
You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.
Use php timestamp for the job :
echo date("H:i:s", ($end_timestamp - $start_timestamp));
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");
The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode(':', $time1);
list($h2,$m2) = explode(':', $time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
echo $time_diff;

Categories