Skip to content

Instantly share code, notes, and snippets.

@AifeiI
Last active July 24, 2019 03:58
护照有效期计算
import java.util.*
/**
* Created by AifeiI on 2019/7/19.
*/
object LeapYearUtil {
fun getDateByAddYears(basicDate: Date, years: Int): Date {
val calendar = Calendar.getInstance()
calendar.time = basicDate
val basicYear = calendar[Calendar.YEAR]
val basicMonth = calendar[Calendar.MONTH]
val basicDay = calendar[Calendar.DAY_OF_MONTH]
var leapYearCounter = 0
for (i in 0 until years + 1) {
val theYear = basicYear + i
if (isLeapYear(theYear)) {
leapYearCounter++
println("Leap Year: $theYear")
}
}
if (isLeapYear(basicYear)) {
if (basicMonth > 1) {
leapYearCounter--
}
}
if (isLeapYear(basicYear + years)) {
if (basicMonth < 1 || (basicMonth == 1 && basicDay < 28)) {
leapYearCounter--
}
}
val days = 365 * years + leapYearCounter
val newTimestamp = calendar.timeInMillis + (days * 24 * 60 * 60 * 1000L)
calendar.timeInMillis = newTimestamp
return calendar.time
}
fun isLeapYear(year: Int): Boolean {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment