Working with Dates in Kotlin: Overview of Libraries and Tools
Working with dates and times is one of the key tasks in modern development. Kotlin, being a modern language, provides several powerful ways to manage dates. In this article, we will look at the main libraries and approaches that will help you work effectively with dates in Kotlin projects, including Android development and server applications.
1. Standard java.time Library (Java 8+)
Starting with Java 8, developers gained access to a completely redesigned API for working with dates — java.time. Since Kotlin is fully compatible with Java, you can use this powerful tool directly. This is the most common method for server-side Kotlin applications.
Main classes:
LocalDate— date without time (year, month, day)LocalTime— time without dateLocalDateTime— date and time without time zoneZonedDateTime— date and time with time zoneInstant— a moment in time in UTCDurationandPeriod— for working with intervals
import java.time.LocalDateimport java.time.LocalDateTimeimport java.time.format.DateTimeFormatter
fun main() { // Current date val today = LocalDate.now() println("Today: $today")
// Creating a specific date val birthDate = LocalDate.of(1990, 5, 15) println("Birth date: $birthDate")
// Formatting val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") val formatted = today.format(formatter) println("Formatted date: $formatted")
// Parsing a string val parsedDate = LocalDate.parse("2024-01-01") println("Parsed date: $parsedDate")
// Working with date and time val now = LocalDateTime.now() println("Now: $now")}2. kotlinx-datetime — Official Library from JetBrains
For projects using Kotlin Multiplatform, the standard kotlinx-datetime library is the best choice. It provides a unified API for all platforms (JVM, JS, Native, Android).
Adding dependency (build.gradle.kts):
dependencies { implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.1")}Main features:
Instant— a moment in timeLocalDateTime— local date and timeLocalDate— local dateLocalTime— local timeTimeZone— time zonesDateTimePeriod— time period
import kotlinx.datetime.*
fun main() { // Current date and time val now = Clock.System.now() println("Current moment: $now")
// Conversion to local components val localDateTime = now.toLocalDateTime(TimeZone.currentSystemDefault()) println("Local time: $localDateTime")
// Creating a date val date = LocalDate(2024, 12, 25) println("Date: $date")
// Formatting val formatted = localDateTime.toString() println("String representation: $formatted")
// Parsing val parsed = Instant.parse("2024-01-01T12:00:00Z") println("Parsed Instant: $parsed")
// Working with time zones val moscowTime = now.toLocalDateTime(TimeZone.of("Europe/Moscow")) println("Moscow time: $moscowTime")}3. ThreeTenABP — for Android Backward Compatibility
If your application supports Android API below 26 (Android 8.0), you cannot use java.time directly. In this case, the ThreeTenABP<