closestTo
value is show in terminal but could not be utilized in the program
#3016
Answered
by
fturmel
emadbaqeri
asked this question in
Q&A
-
Hey folks, I'm trying to find the closest date based on today. I have used import * as dateFns from 'date-fns';
const today = new Date().getTime();
const dates = [
2022-04-10T14:07:12.276Z,
2022-04-10T14:07:06.967Z,
2022-04-10T14:07:04.663Z,
2022-04-10T14:07:03.040Z,
2022-04-10T14:07:01.420Z,
2022-04-10T14:06:59.869Z,
2022-04-10T14:06:53.223Z
]
const closestIndex = dateFns.closestTo(today, dates);
console.log(closestIndex); // => 0
console.log(dates[closestIndex]); // => undefined could not be used as index value |
Beta Was this translation helpful? Give feedback.
Answered by
fturmel
May 16, 2022
Replies: 1 comment 1 reply
-
Hi @emadbaqeri, Please refer to the docs to see the proper function usage.
https://date-fns.org/docs/closestTo import { closestIndexTo } from "date-fns";
const today = new Date();
const dates = [
new Date("2022-04-10T14:07:12.276Z"),
new Date("2022-04-10T14:07:06.967Z"),
new Date("2022-04-10T14:07:04.663Z"),
new Date("2022-04-10T14:07:03.040Z"),
new Date("2022-04-10T14:07:01.420Z"),
new Date("2022-04-10T14:06:59.869Z"),
new Date("2022-04-10T14:06:53.223Z")
];
const closestIndex = closestIndexTo(today, dates);
console.log(closestIndex); // 0
console.log(dates[closestIndex].toISOString()); // 2022-04-10T14:07:12.276Z
console.log(closestIndexTo(today, [])); // undefined |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
emadbaqeri
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @emadbaqeri,
Please refer to the docs to see the proper function usage.
closestTo
returns a date, whileclosestIndexTo
returns an index.undefined
, it's likely because the array of dates passed to the function was empty.https://date-fns.org/docs/closestTo
https://date-fns.org/docs/closestIndexTo