例如说我们看一下01/2018的日期......
那个月有5个星期三,所以我们将返回' 01/17/2018'因为它属于该月的第3个星期三
但是,如果我们看看02/2018 ......
那个月有4个星期三,所以我们将返回' 02/14/2018'因为它属于该月的第二个星期三
中点公式在这里不起作用(至少我不认为这样做)
这是我应该如何规划一切,还是有更简单的方法?
function returnMidWednesday(month, year){
//How many days in month
var daysInMonth = new Date(year,month,0).getDate();
//How many Wednesdays in that month
//If Wednesdays total == 4 return 2nd
//If Wednesdays total == 5 return 3rd
}
答案 0 :(得分:2)
假设一个月中的日期与本月的第一天一样变化,该算法可能不够简单。有几个月有28天,29天,30天和31天。最后三个星期三可以有4个或5个星期。
一种算法是:
这是一个实现:
/* Return second Wednesday where there are 4 in a month
** Return the third Wednesday where there are 5 in a month
** @param {number} year - year
** @param {number} month - month
** @returns {Date} date of "middle" Wednesday
*/
function getMidWed(year, month) {
// Create date for first of month
var d = new Date(year, month - 1);
// Set to first Wednesday
d.setDate(d.getDate() + ((10 - d.getDay()) % 7));
// Get days in month
var n = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
// Set to 3rd Wed if 28 or more days left, otherwise 2nd
d.setDate(d.getDate() + (n - d.getDate() > 27? 14 : 7));
return d;
}
// Some tests
[[2000,2], [2000,5], [2012,2], [2012,5], [2018,1], [2018,2]].forEach(
function(a) {
console.log(getMidWed(a[0], a[1]).toString());
}
);

答案 1 :(得分:0)
从0和年开始传递月份到此方法,它将在日/蛾/年formte中在控制台中打印中间日期
function returnMidWednesday(month, year) {
var date = new Date(year, month, 1);
if (date.getDay() != 0 && date.getDay() <= 3) {
//month has 5 wed
// 3 means wed day index from week
var day = 21 - (date.getDay() + 3);
console.log(day + "/" + (month + 1) + "/" + year);
} else {
//month has 4 wed
// 3 means wed day index from week
//7 means total number of days in week
var day = 14 - (date.getDay() + 3) % 7;
console.log(day + "/" + (month + 1) + "/" + year);
}
}