我在Javascript中有一系列日期,我需要过滤掉一周内的日期。
HTML5 input tag支持type ="周"它返回格式为YYYY-WW
的字符串,即四位数年份,后跟两位数ISO week date。
例如周2017-1
周于2017年1月2日星期一至2017年1月8日星期日之间。
如何选择html5周输入中指定的一周内的日期?
const dates = [
new Date('2016-12-07T22:10:50.855Z'),
new Date('2017-01-25T09:47:15.109Z'),
new Date('2016-12-23T17:36:26.309Z'),
new Date('2016-12-28T22:06:22.459Z'),
new Date('2016-12-26T14:04:12.874Z'),
new Date('2016-12-15T06:32:42.628Z'),
new Date('2017-01-18T08:14:43.478Z'),
new Date('2017-01-07T03:37:54.351Z'),
new Date('2017-01-05T04:05:52.437Z'),
new Date('2017-01-13T20:42:04.034Z'),
new Date('2016-12-31T10:55:47.552Z'),
new Date('2017-01-21T02:44:11.275Z'),
new Date('2016-12-20T18:09:35.298Z'),
new Date('2017-01-06T11:52:59.413Z'),
new Date('2017-01-12T02:40:56.888Z'),
new Date('2016-12-17T03:41:15.191Z'),
new Date('2016-12-18T01:30:40.727Z'),
new Date('2016-12-28T08:12:10.745Z'),
new Date('2017-01-19T11:25:56.199Z'),
new Date('2017-01-03T13:17:14.474Z'),
new Date('2017-01-11T07:00:57.338Z'),
new Date('2016-12-20T01:22:55.865Z'),
new Date('2017-01-11T23:42:48.051Z'),
new Date('2016-12-29T20:04:20.385Z'),
new Date('2017-01-18T13:21:48.257Z')
]
const week = '2017-01'
// given a date and a range
// return true if date falls within range
// otherwise return false
const fallsWithinRange(date, week) {
// magical function yet to be discovered here
}
const filteredDates = dates.filter((date)=>fallsWithinRange(date, week));
答案 0 :(得分:0)
改编自this SO answer:
const fallsWithinRange = (date, week) => {
const y = week.split('-')[0];
const w = week.split('-')[1];
const startDays = 3 + (w - 1) * 7 - (new Date(y,0,1)).getDay();
const startDay = new Date(y, 0, startDays);
const endDays = 9 + (w - 1) * 7 - (new Date(y,0,1)).getDay();
const endDay = new Date(y, 0, endDays);
return (date >= startDay && date <= endDay);
};