Created
April 25, 2018 02:39
-
-
Save granoeste/00b2963542179dbdd6ea166b314f20fb to your computer and use it in GitHub Desktop.
get day of week in month
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DateUtils { | |
static DateTime dayOfWeekInMonth(int year, int month, int times, int weekday) { | |
// 指定年月の1日の日付 | |
var dt = new DateTime(year, month, 1); | |
// 指定週の日 (1週目->1,2週目->8,3週目->15,4週目->22,4週目->29) | |
var day = (times - 1) * 7 + 1; | |
// 指定年月の1日の曜日と指定曜日の差 | |
var offset = weekday - dt.weekday; | |
// 日を補正 | |
if (offset < 0) { | |
day += offset + 7; | |
} else { | |
day += offset; | |
} | |
// 該当の日付 | |
var dayOfWeekInMonth = new DateTime(year, month, day); | |
// 翌年/翌月の場合はnullを返す | |
if (dayOfWeekInMonth.year > year || dayOfWeekInMonth.month > month) { | |
return null; | |
} | |
return dayOfWeekInMonth; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment