Skip to content

Instantly share code, notes, and snippets.

@V-Abhilash-1999
Created October 30, 2023 16:17
Show Gist options
  • Save V-Abhilash-1999/a7234557a71493ffb4cc7a36e54ba1bf to your computer and use it in GitHub Desktop.
Save V-Abhilash-1999/a7234557a71493ffb4cc7a36e54ba1bf to your computer and use it in GitHub Desktop.
//firstDayOfWeek contains when the week starts in the locale.
//For example, UK locale will have Monday as first day of week
//English locale will have Sunday as first day of week.
val firstDayOfWeek = currentMonth.firstDayOfWeek
//weekDayList contains a list of week days with size 7
//that starts with the firstDayOfWeek.
//For example, the UK locale has MONDAY as first day of week.
//The value of Calendar.MONDAY is 2.
//So the list contains [2, 3, 4, 5, 6, 7, 1]
val weekDayList = (0..6).map { ((firstDayOfWeek + it) % 7).takeIf { it > 0 } ?: 7 }
//firstDayOfMonth contains the week day in which the month starts.
//For Example November 2023 starts in Wednesday.
//So the value will be 4.
val firstDayOfMonth = remember (year, month, locale){
Calendar.getInstance(locale).apply {
set(Calendar.YEAR, year)
set(Calendar.MONTH, month - 1)
set(Calendar.DAY_OF_MONTH, 1)
}.get(Calendar.DAY_OF_WEEK)
}
//initialDayInWeek of the week will contain the positoin in the row
//where the month should start.
//For example, In UK locale, since wednesday is the third day of week,
//November 2023 should start at the third position in Row
//In English locale, wednesday is at the fourth day so the same month should
//start at fourth position.
val initialDayInWeek = weekDayList.indexOf(firstDayOfMonth) + 1
//Number of days in current month,
//31 in Jan, Mar etc, 30 in Apr, Jun etc
//28 or 29 in Feb
val totalDaysOfMonth = currentMonth.getActualMaximum(Calendar.DAY_OF_MONTH)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment