Working with Dates in Kotlin: Overview of Libraries and Tools
Working with dates and time is one of the key tasks in most applications. In Kotlin, as a modern multiplatform language, there are several ways to work with dates. In this article, we will look at the main libraries and tools that will help you effectively manage dates, time, intervals, and time zones in Kotlin projects.
1. Standard Java Library: java.time
Since Kotlin is fully compatible with Java, you can use the powerful java.time library (JSR-310), which appeared in Java 8. This is the recommended approach for server and Android applications (starting from API 26+).
Main classes:
LocalDate— date without time (year, month, day).LocalTime— time without date.LocalDateTime— date and time without time zone.ZonedDateTime— date and time with time zone.Instant— a moment in time in UTC (machine time).DurationandPeriod— time intervals.
Usage example:
import java.time.*
fun main() { // Current date and time val now = LocalDateTime.now() println("Now: $now")
// Creating a specific date val birthDate = LocalDate.of(1990, Month.JUNE, 15) println("Date of birth: $birthDate")
// Working with time zones val zonedDateTime = ZonedDateTime.now(ZoneId.of("Europe/Moscow")) println("Time in Moscow: $zonedDateTime")
// Difference between dates val from = LocalDate.of(2023, 1, 1) val to = LocalDate.now() val daysBetween = ChronoUnit.DAYS.between(from, to) println("Days since New Year: $daysBetween")
// Formatting val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm") println("Formatted date: ${now.format(formatter)}")}Advantages: built-in, reliable, full support for all features.
Disadvantages: not supported on older Android (before API 26) without desugaring.
2. kotlinx-datetime (multiplatform library from JetBrains)
For multiplatform projects (KMP), JetBrains created the kotlinx-datetime library. It provides a unified API for all platforms (JVM, Native, JS).
Main classes:
Instant— a moment in time in UTC.LocalDateTime— date+time without time zone.LocalDateandLocalTime.DateTimePeriodandDatePeriod— intervals.TimeZone— time zone.
Usage example:
import kotlinx.datetime.*
fun main() { // Current moment val now = Clock.System.now() println("Current UTC: $now")
// Conversion to local time val localDateTime = now.toLocalDateTime(TimeZone.currentSystemDefault()) println("Local time: $localDateTime")
// Creating a date val date = LocalDate(2024, 12, 25) println("Date: $date")
// Difference between dates val start = LocalDateTime(2024, 1, 1, 0, 0) val end = LocalDateTime(2024, 12, 31, 23, 59) val period = start.periodUntil(end, DateTimeUnit.DAY) println("Days between: $period")
// Formatting (requires a separate library or manual approach) println("Year: ${localDateTime.year}, month: ${localDateTime.monthNumber}")}Advantages: multiplatform, lightweight, official support.
Disadvantages: limited formatting capabilities (no built-in DateTimeFormatter).