Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created March 16, 2022 03:37
Show Gist options
  • Select an option

  • Save miguelmota/28cd8999e8260900140273b0aaa57513 to your computer and use it in GitHub Desktop.

Select an option

Save miguelmota/28cd8999e8260900140273b0aaa57513 to your computer and use it in GitHub Desktop.
JavaScript get nearest date timestamp from list of date timestamps
function nearestDate (dates, target) {
if (!target) {
target = Date.now()
} else if (target instanceof Date) {
target = target.getTime()
}
let nearest = Infinity
let winner = -1
dates.forEach(function (date, index) {
if (date instanceof Date) {
date = date.getTime()
}
let distance = Math.abs(date - target)
if (distance < nearest) {
nearest = distance
winner = index
}
})
return winner
}
// usage:
// const index = nearestDate(dates, timestamp)
@frayhan94
Copy link

helpful thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment