The following code will return the difference between two Carbon dates in minutes:
$carbonNow = Carbon::now();
$diff = $carbonNow->diffInMinutes($someRandomFutureDateVariable);
Which will return a single minute result. But I'm trying to get the difference in a 15 minute increments - such as every timestamp for every 15 minute increment in the result. Pseudo code would be:
[
'2020-10-15 12:45:00',
'2020-10-15 13:00:00',
'2020-10-15 13:15:00',
'2020-10-15 13:30:00',
...
]
In addition, I'd like to be able to set the time difference, so if I didn't want to target a 15 minute increment I could target whatever increment I pass into my function. I'm able to get the difference between two dates, but stuck on returning timestamps per each increment.
carbon::diffInMinutes delivers the minutes and removes the seconds.
The minute difference for a given minute increment can easily be calculated as follows:
$inc = 15; //15 minutes
$carbonNow = Carbon::now();
$diff = $carbonNow->diffInMinutes($someRandomFutureDateVariable);
$diffInc = $diff - $diff%$inc;
Related
I'm trying to run a query where a check is done if a time is in between a time and that time + 90 mins.
I have 1 time value being passed in. So lets say the time being passed in is 1pm. I'd like to check if a time is between 1pm and 2.30pm.
I have tried passing in a second param adding the seconds with strtotime() and I have the below
AND r.start_time BETWEEN '19:00:00.0000' AND '19:00:00.0000', INTERVAL + 90 MINUTE
I think you can use strtotime(...)+5400 to express 90 minutes.
For example:
$times = strtotime('19:00:00.0000');
$end_time = $times + 5400;
$query = "SELECT ... WHERE r.start_time BETWEEN '$times' AND '$end_times'";
I have created an array with 10 timestamps each 1 day apart:
$data_points = array();
$now = time();
$one_day = 60 * 60 * 24;
for($i = 1; $i <= 10; ++$i) {
$key = $now - ($one_day * $i);
$data_points[$key] = 0;
}
print_r($data_points);
Array
(
[1328642414] => 0
[1328556014] => 0
[1328469614] => 0
[1328383214] => 0
[1328296814] => 0
[1328210414] => 0
[1328124014] => 0
[1328037614] => 0
[1327951214] => 0
[1327864814] => 0
)
Now I have a array of tasks that have started at various times in the last 10 days, I want to see which day my task fell into.
I was going to loop through each $data_point and see if the start time is greater than the current day and less than the next, then increment that data point
is there a better way to do this?
Thanks
Well, to reduce your search time you could put your data into a binary search tree rather than a simple array.
Whether or not that's worth the trouble depends on how big your data set is. Of course, you'd also have to re-balance your tree every so often as you add new dates.
I think there's a better method.
Assuming you have task starting timestamps in an array, the algorithm will be something like :
for each task starting timestamp
timestamp <- $now - timestamp // you will obtain task age in seconds
timestamp <- timestamp / (60*60*24) // you will obtain task age in days
// round resulting timestamp with a precision of 0 if you want to obtain the task age in integer days.
end for each
In this way you will loop on only one array. This will be less expensive than your method.
Obviously, if your tasks come from a SQL database, there will be a greater solution in SQL.
You can use DateTime class
$now = new DateTime();
$task = new DateTime('2012-02-20');
$interval = $taks->diff($now);
echo 'Here is the position you need:' . $interval->format('%R%a days');
** Updated to avoid use of DateTime as asked in comment **
$now = date('Ymd');
$task = date('Ymd',$tasktime);
$interval = $task - $now;
The interval is the number you expect.
I know this question is old, but since there are no accepted answers, and it seems like a fun question to answer - here we go!
Based on your question, your algorithm has the Big O of O(10n) where n is the number of tasks. This means, that it is fairly efficient compared to a lot of things. As pointed out, a binary search tree would be faster having O(log(n)), however implementing it wouldn't really be worth the saved time during processing. Though, you can make it slightly more efficient and have a resulting O(n) by using something like:
$now = time();
$oneDay = 86400; //60 * 60 * 24
foreach($tasks as $task) {
//assuming now that $task is the timestamp of the task
//extra paranthesis added for easier reading
$dif = $now - ($oneDay * ceil(($now - $task) / $oneDay));
$data_points[$dif]++;
}
The math in the diff is as follows. $now-$task is the difference between the two timestamps in seconds, we divide by $oneDay to get the number of days in the past the task occurred. Now, assuming that $now is the start of a new day, and if an event happened just 12 hours ago it was 'yesterday', we use ceil to round it to the next integer so '.5' becomes '1'. From there, we multiply by $oneDay to get the number of seconds of the days that have passed - to work with the $data_points array that you previously created. We then take that result and subtract it from $now, again to work with your $data_points array. That result gives us a time stamp that we can use that matches those in the array you created, and we use it as the 'key' for it and increment accordingly.
This will prevent you from having to loop through the entire $data_points array for each task, and thus reducing its complexity from O(10n) to O(n).
Anyways, I hope that answer helps explain why your formula isn't that inefficient, but shows how to make it ever so slightly more efficient.
I'm using PHP + mongoDB.
How can I get a time difference between two time values?
I have a real time value which is string
$realtime = "2010-01-01 12:00:00";
and another value which is unixstamp time,
$mongotime = new Mongodate(strtotime($realtime));
So I can use either a string time value or unix time stamp.
But I'm not sure the way to get time difference between two values.
Should I just subtract two $mongotime values and does it give me a time difference in seconds?
If you have 2 unix timestamps...
$date = $item['pubdate'];
(etc ...)
$unix_now = time();
$result = strtotime($date, $unix_now);
$unix_diff_min = (($unix_now - $result) / 60);
$min = round($unix_diff_min);
This will give number of mins between the 2 timestamps...
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.