Skip to content

Instantly share code, notes, and snippets.

@ahmadmust8
Last active February 22, 2019 02:17
Show Gist options
  • Save ahmadmust8/8ba255092f3e3c75340e1f400cb3d5c4 to your computer and use it in GitHub Desktop.
Save ahmadmust8/8ba255092f3e3c75340e1f400cb3d5c4 to your computer and use it in GitHub Desktop.
Method To get Last Day Of Any Given Month
fun isLeapYear(year: Int): Boolean {
return year % 4 == 0
}
fun getLastDayOfMonth(month: Int,year: Int = 0) : Int {
when (month) {
JANUARY-> return 31
FEBRUARY-> {
// current time
val now = Calendar.getInstance()
now.timeInMillis = System.currentTimeMillis()
val currentYear= if (year == 0) now.get(Calendar.YEAR) else year
// last day of FEBRUARY for this year
val lastDayOfFebruaryInOfTheGivenYear = Calendar.getInstance().run {
set(Calendar.YEAR, currentYear)
set(Calendar.MONTH, FEBRUARY)
set(Calendar.DAY_OF_MONTH, 28)
set(Calendar.HOUR, 11)
set(Calendar.MINUTE, 59)
set(Calendar.SECOND, 59)
set(Calendar.AM_PM, Calendar.PM)
timeInMillis
}
//chick if the FEBRUARY for this year is passed or not
val isFebruaryForThisYearPassed = lastDayOfFebruaryInOfTheGivenYear > now.timeInMillis
//if FEBRUARY for this year has been passed then it's the next year
val isItLeapYear = if (isFebruaryForThisYearPassed) currentYear else (currentYear + 1)
return if (isLeapYear(isItLeapYear)) {
29
} else {
28
}
}
MARCH-> return 31
APRIL-> return 30
MAY-> return 31
JUNE-> return 30
JULY-> return 31
AUGUST-> return 31
SEPTEMBER-> return 30
OCTOBER-> return 31
NOVEMBER-> return 30
DECEMBER-> return 31
else -> return 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment