Skip to content

Instantly share code, notes, and snippets.

@TeWu
Last active September 12, 2017 08:17
Show Gist options
  • Save TeWu/9717c04d5de52d0161b8c74348d801a8 to your computer and use it in GitHub Desktop.
Save TeWu/9717c04d5de52d0161b8c74348d801a8 to your computer and use it in GitHub Desktop.
Half-BirthDate Calculator (halfbirthday)
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
object HalfBirthdate {
val date_2000_02_29: LocalDateTime = LocalDateTime.parse("2000-02-29T00:00:00")
case class HalfBirthdate(earlierHalfBirthDate: LocalDateTime, laterHalfBirthDate: LocalDateTime) {
def show() {
println("Earlier half-BirthDate: " + format(earlierHalfBirthDate))
println("Later half-BirthDate: " + format(laterHalfBirthDate))
}
def format(datetime: LocalDateTime) = datetime.format(DateTimeFormatter.ofPattern("dd.MM HH:mm:ss"))
}
def halfBirthDate(birthDate: LocalDateTime): HalfBirthdate = {
if (birthDate.getDayOfMonth == 29 && birthDate.getMonthValue == 2) throw new IllegalArgumentException("Can't calculate halfBirthDate when birthDate is on leap day (29.02)")
val leapBirthDate = birthDate.withYear(2000)
val shorterYear = birthDate.withYear(2001)
val longerYear =
if (leapBirthDate.isBefore(date_2000_02_29)) leapBirthDate
else leapBirthDate.minusYears(1)
HalfBirthdate(shorterYear.plusDays(182).plusHours(12),
longerYear.plusDays(183))
}
def main(args: Array[String]) {
val birthDate = LocalDateTime.parse("2000-09-15T00:00:30")
halfBirthDate(birthDate).show()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment