The cleanest way to tell if 3 times in half an hour from each other

I have 3 date / time input fields on the form, and the user cannot select any time within half an hour from each other.

I converted all the values ​​to epoch format using the strtotime implementation in Javascript, but am not sure how to recursively check that any time is actually half an hour.

I can pass all the checks, but it would be easier to write a recursive function (especially if theoretically there were more than 3 time intervals).

Was there any kind of Google research, but he was out of luck.

Any suggestions for implementing this in Javascript or JQuery.

Thanks.

+4
source share
3 answers

Sort the time, then look at the neighboring elements and see if they are within 30 minutes (1800 seconds) of each other.

EDIT: I'm embarrassed to worry about sending the sample code at all, but if your time is in an array called times :

  times.sort ();
 for (i = 0; i <times.length-1, i ++) {
   if (times [i + 1] - times [i] <1800) {
     return false;
   }
   return true;
 }
+5
source

Pseudo code ...

 epochArrayOfTimes.sort(); for (i = 0, k = 1; k <= epochArrayOfTimes.size(); i++, k++) { if ( (epochArrayOfTimes[i] - epochArrayOfTimes[k]) <= 30 minutes) { alert/error } } 
+1
source

First, I want to say that I am not good at JavaScript. Therefore, if this is not so, please do not let me into oblivion.

JavaScript:

 var time = ["1270690925", "1270696925", "1273696925"]; var spaceTime = 60 * 30; for (var i in time) { for (var j in time) { if (time[i] - time[j] < spaceTime) alert("You must put a greater length between these two times: " + time[i] + " and " + time[j] + "."); } } 

Based on this PHP code:

 function timeCheck($timeArrays = array(), $spaceTime = 1800) { foreach ($timeArray as $time1) { foreach ($timeArray as $time2) { if ($time1 - $time < $spaceTime) { # These items are not appropriately spaced. } } } } 

Attempt No. 2 (after viewing comments) in PHP:

 function timeCheck($times = array(), $interval = 1800) { sort($times); for ($i = 0, $j = 1, $k = count($times); $j < $k; ++$i, ++$j) { if (($times[$j] - $times[$i]) < $interval) { echo "{$times[$i]} is less then $interval away from {$times[$j]}." . PHP_EOL; } } } 
0
source

Source: https://habr.com/ru/post/1306324/


All Articles