简体   繁体   English

如何在Javascript中根据星期几的名称获取日期?

[英]How can I get dates given the name of the day of the week in Javascript?

Suppose I have the name of the day of the week like 'Wednesday' or 'Monday' , is there a way to get the dates of a month returned related to the given day of the week?假设我有一周中某天的名称,如'Wednesday''Monday' ,有没有办法获取与一周中给定日期相关的月份日期?

For instance in the given calendar below, is there a way to get the dates [2,9,16,23,30] for the day of 'Wednesday' in September 2020?例如,在下面给定的日历中,有没有办法获得 2020 年 9 月“星期三”这一天的日期[2,9,16,23,30] The solution doesn't have to exactly match this as long as it returns the proper dates for the given day:只要它返回给定日期的正确日期,解决方案就不必完全匹配:

在此处输入图片说明

Have a go with this试试这个

 const dayNames = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","), days = [...Array(32).keys()].splice(1); // generate 1-31 const getDates = (yyyy, mm, dayName) => { const dayNumber = dayNames.indexOf(dayName); mm -= 1; // JS months start at 0 return days.filter(d => { const date = new Date(yyyy, mm, d); return mm === date.getMonth() && dayNumber === date.getDay() }); }; console.log( getDates(2020, 9, "Wednesday") ) console.log( getDates(2020, 9, "Monday") )

 /* Without the need for a dayName array but needing the month name as input **NOTE** this was more for my own entertainment - the date constructor may fail on some browsers that does not like `new Date("Monday, August 31")` such as Safari */ const fm = new Intl.DateTimeFormat('en-US',{dateStyle:"full"}), days = [...Array(32).keys()].splice(1); // generate 1-31 const getDates = (yyyy, monthName, dayName) => { const mn = monthName.slice(0,3); return days.filter(d => { const [,dn,month,day] = fm.format(new Date(`${mn} ${d}, ${yyyy}`)).match(/(\\w+?), (\\w+?) (\\d+?),/) return dayName===dn && monthName === month; }); }; console.log( getDates(2020, "September", "Wednesday") ) console.log( getDates(2020, "August", "Monday") );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM