Skip to content

Instantly share code, notes, and snippets.

@hungyanbin
Created November 18, 2017 03:24
Show Gist options
  • Save hungyanbin/5b9fdfdc62b1c7f1b8f4bfcd7958b69f to your computer and use it in GitHub Desktop.
Save hungyanbin/5b9fdfdc62b1c7f1b8f4bfcd7958b69f to your computer and use it in GitHub Desktop.
object LocalDateTimeUtils {
//Calendar to LocalDate
@JvmStatic
fun toLocalDate(calendar: Calendar): LocalDate {
return LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH))
}
//Date to LocalDate
@JvmStatic
fun toLocalDate(date: Date): LocalDate{
val instant = DateTimeUtils.toInstant(date)
return instant.atZone(ZoneId.systemDefault())
.toLocalDate()
}
//Date to LocalTime
@JvmStatic
fun toLocalTime(date: Date): LocalTime {
val instant = DateTimeUtils.toInstant(date)
return instant.atZone(ZoneId.systemDefault())
.toLocalTime()
}
//Date to LocalDateTime
@JvmStatic
fun toLocalDateTime(date: Date): LocalDateTime {
val instant = DateTimeUtils.toInstant(date)
return instant.atZone(ZoneId.systemDefault())
.toLocalDateTime()
}
//LocalDateTime to Date
@JvmStatic
fun toDate(dateTime: LocalDateTime): Date{
val instant = dateTime.atZone(ZoneId.systemDefault()).toInstant()
return DateTimeUtils.toDate(instant)
}
//LocalDate to Date
@JvmStatic
fun toDate(dateTime: LocalDate): Date{
val instant = dateTime.atTime(0, 0).atZone(ZoneId.systemDefault()).toInstant()
return DateTimeUtils.toDate(instant)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment