var year = 2017;
var month = 4;
var startDayOfWeek = START_SUNDAY;
var week = 6;
/*
if(!year.matches(^\d{4}$))) return;
if(!month.matches(^\d*$)) return;
if(!(startDayOfWeek == START_SUNDAY) || (startDayOfWeek == START_MONDAY))) return;
*/
console.log(year + "年" + month + "月は" + countWeekOfMonth(year, month, startDayOfWeek) + "週です。");
console.log(year + "年" + month + "月(開始曜日 : " + startDayOfWeek + ")の、週開始日は" + getFirstDateOfNthWeekOfMonth(year, month, startDayOfWeek, week) + "日です");
// monthは日本式 1月 → month=1
function countWeekOfMonth(year, month, startDayOfWeek) {
var daysOfMonth = new Date(year, month, 0).getDate();
var day = new Date(year, month-1, 1).getDay(); // 今月の1日の曜日
var weekCount = 1;
for(var i=1; i<daysOfMonth; ++i){// 今月の2日目からカウント
if((day+i)%7 == startDayOfWeek) weekCount++;
}
return weekCount;
}
function getFirstDateOfNthWeekOfMonth(year, month, startDayOfWeek, n) {
if(n == 1){
return new Date(year, month-1, 1);
}
var daysOfMonth = new Date(year, month, 0).getDate();
var day = new Date(year, month-1, 1).getDay(); // 今月の1日の曜日
var weekCount = 1;
for(var i=1; i<daysOfMonth; ++i){// 今月の2日目からカウント
if((day+i)%7 == startDayOfWeek) weekCount++;
if(weekCount == n) return new Date(year, month-1, i+1).getDate();
}
}
function daysOfMonth(year, month) {
return new Date(year, month, 0).getDate();
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme