[英]How can I get dates given the name of the day of the week in Javascript?
试试这个
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.