How can I find the closest time to the current time from an array using momentjs?
I have an array of values [180, 360, 540, 720, 900, 1080, 1260]
. Each element of the array describes the number of minutes after midnight UTC.
Using momentjs , how can I find the element of the array closest to the current time 'Europe/London'
?
So far I've managed to get the current time 'Europe/London'
using moment-timezone.js :
var currentTime = moment().tz('Europe/London');
But now I am trying to find the closest array element to currentTime
.
source to share
If at all possible, you should keep the value in UTC until you're ready to format. The time zone, along with the date format, is usually a part of the localization, not something you want to embed too deeply into your business logic. Note that there were time slots that changed the local time flow, which is a nightmare for everyone.
With your input and comparison data as in UTC, you can simply sort the array by absolute difference:
var now = moment.utc();
var target = now.hours() * 60 + now.minutes();
var data = [180, 360, 540, 720, 900, 1080, 1260]
var sorted = data.sort(function(a, b) {
var dA = Math.abs(a - target),
dB = Math.abs(b - target);
if (dA < dB) {
return -1;
} else if (dA > dB) {
return 1;
} else {
return 0;
}
});
document.getElementById('r').textContent = JSON.stringify(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<pre id="r"></pre>
Then the first element will be the closest, and the rest will remain in order of distance.
source to share