如何使用时刻js获得某个月的第二个星期二或获得某个月的第三个星期四。
我尝试找到一个解决方案,但没有成功。我自己写了并在下面发布了答案,如果你有更好的解决方案,你可以回答你的实施。
答案 0 :(得分:2)
//get a preferred day of a month
var getGivenDateOfMonth = function (startDate, dayOfWeek, weekNumber) {
var startOfMonth = moment(startDate).utc().startOf('month').startOf('isoweek');
var dayOne = moment((moment(startDate, "YYYY-MM-DD").format("YYYY-MM") + "-01"),"YYYY-MM-DD");
var studyDate;
if (dayOne.isoWeekday() === 1) {
studyDate = moment(startDate).utc().startOf('month').startOf('isoweek').add(dayOfWeek - 1, 'days')
.add(weekNumber, 'w');
}
else if (dayOne.isoWeekday() <= dayOfWeek) {
studyDate = moment(startDate).utc().startOf('month').startOf('isoweek').add(dayOfWeek - 1, 'days')
.add(weekNumber - 1, 'w');
} else {
studyDate = moment(startDate).utc().startOf('month').startOf('isoweek').add(dayOfWeek - 1, 'days')
.add(weekNumber, 'w');
}
if (studyDate.month() == startOfMonth.month()) {
studyDate = studyDate.subtract(1, 'w');
}
return studyDate;
};
startDate 是指定月份的日期。
dayOfWeek 是js ISO星期和星期的时刻
weeknumber 是您想要的周数(1,2,3,4)
答案 1 :(得分:2)
这是我在评论中链接的答案的更新版本。我使用weekday
来使用一周中属于区域设置的日期,如果您总是希望星期日为0,星期六为6 ,则可以使用day
。
var getGivenDateOfMonth = function (startDate, dayOfWeek, weekNumber) {
// Start of the month of the given startDate
var myMonth = moment(startDate).startOf('month');
// dayOfWeek of the first week of the month
var firstDayOfWeek = myMonth.clone().weekday(dayOfWeek);
// Check if first firstDayOfWeek is in the given month
if( firstDayOfWeek.month() != myMonth.month() ){
weekNumber++;
}
// Return result
return firstDayOfWeek.add(weekNumber-1, 'weeks');
}
// Examples
var secondMondayOfJuly = getGivenDateOfMonth('2017-07-10', 1, 2);
console.log(secondMondayOfJuly.format());
var thirdFridayOfJuly = getGivenDateOfMonth('2017-07-10', 5, 3);
console.log(thirdFridayOfJuly.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
答案 2 :(得分:0)
function nthDayOfMonth(month, year, day, weekNum){
var nearestDay = moment(month + " " + year,"M YYYY").day(day);
var nthDay = nearestDay.add(nearestDay.isSame(moment({month: month}),"month") ? weekNum - 1 : weekNum ,"weeks");
return nthDay;
}
document.write(nthDayOfMonth(7,2017,3,3).format("L"));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
&#13;
答案 3 :(得分:0)
获取本月第二个星期二的日期:
var date = new Date();
var month_week = 2; // 2nd Week
var week_day = 2; // Tuesday
var first_week = moment(date).startOf("month").day(week_day);
var result = first_week.add(7 * (month_week - 1), "days");
console.log(result);
<script src="https://momentjs.com/downloads/moment.min.js"></script>