0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascript 完全個人用

Posted at
		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();
		}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?