[英]Suggest Next available date(closest) but don't suggest dates which are in array
I have a list of array exdate which has some date.我有一个包含某个日期的数组exdate列表。 I want to exclude those dates and suggest the next available date from today.
我想排除这些日期并建议从今天开始的下一个可用日期。 Date should not be random.
日期不应该是随机的。
const exdate = ["24/08/2020", "8/8/2020"] //dates needs to be excluded [DD/MM/YYYY]
The newly generated date would be "25/08/2020" which is the closest one and not in the array.新生成的日期将是“25/08/2020”,这是最接近的日期,并且不在数组中。
This post has a question that is generating a random date using math.random function but my scenario is different.这篇文章有一个问题是使用math.random函数生成随机日期,但我的情况不同。
Iterate inside a while loop and check if exdate contains the current date.在 while 循环中迭代并检查 exdate 是否包含当前日期。 If it doesnt contain the date, add 1 day to the current date and check it again.
如果它不包含日期,则在当前日期上加 1 天并再次检查。 If the current date is not present inside the exdate array, exit the while loop and print the value.
如果当前日期不存在于 exdate 数组中,则退出 while 循环并打印该值。
A thing you might consider: What is the expected format of your dates?您可能会考虑的一件事:您的日期的预期格式是什么? You should make sure it stays consistent.
你应该确保它保持一致。 eg dont use leading 0s in front of months.
例如,不要在几个月前使用前导 0。 My answer should point you into the right direction.
我的回答应该为您指明正确的方向。
exdate = ['24/8/2020', '8/8/2020']; let currDate = new Date(); let dd = currDate.getDate(); let mm = currDate.getMonth() + 1; let y = currDate.getFullYear(); let dateFormat = dd + '/' + mm + '/' + y; while (true) { dd = currDate.getDate(); mm = currDate.getMonth() + 1; y = currDate.getFullYear(); dateFormat = dd + '/' + mm + '/' + y; if (!exdate.includes(dateFormat)) break; currDate.setDate(currDate.getDate() + 1); } console.log(dateFormat);
I think this code does what you are after and is quite simple:我认为这段代码可以满足您的要求并且非常简单:
import moment from "moment";
// Constants
const dateFormat = 'DD/MM/YYYY'
// Utils
const strToDate = (date) => moment(date, dateFormat)
const dateToStr = (date) => date.format(dateFormat)
const sortByMoment = (a, b) => b.diff(a)
const incrementDate = (date) => date.add(1, 'day')
const isToday = (date) => moment().isSame(date, 'day')
// Data
const exdate = ["17/08/2020", "24/08/2020", "8/8/2020"];
// Implementation
const sortNewestToOldest = (data) => data
.map(strToDate)
.sort(sortByMoment)
const nextAvailableDate = ([head]) => isToday(head) ? [dateToStr(incrementDate(head))] : [dateToStr(moment())]
nextAvailableDate
check if todays date is in the exdate
list, if yes return tomorrow, else return today. nextAvailableDate
检查今天的日期是否在exdate
列表中,如果是明天返回,否则返回今天。 If you also had future dates in there that you need to accomodate for you could expand isToday
to be isTodayOrInTheFuture
.如果你在那里还有未来的日期,你需要适应你可以将
isToday
扩展为isTodayOrInTheFuture
。 The moment functions you would need can all be found here .您需要的矩函数都可以在这里找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.