kotlinbeginner

Date and Time Operations in Kotlin

Work with dates and times using java.time: parsing, formatting, duration, period, and timezone handling.

kotlin
import java.time.*
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

fun main() {
    // Current date and time
    val now = LocalDateTime.now()
    val today = LocalDate.now()
    val currentTime = LocalTime.now()
    println("Now: $now")
    println("Today: $today")
    println("Time: $currentTime")

    // Create specific dates
    val birthday = LocalDate.of(1990, Month.MARCH, 15)
    val meeting = LocalDateTime.of(2024, 6, 15, 14, 30)
    println("Birthday: $birthday")
    println("Meeting: $meeting")

    // Formatting
    val formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy HH:mm")
    println("Formatted: ${now.format(formatter)}")

    val isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
    println("ISO: ${now.format(isoFormatter)}")

    // Parsing
    val parsed = LocalDate.parse("2024-03-15")
    val parsedCustom = LocalDateTime.parse("March 15, 2024 14:30", formatter)
    println("Parsed: $parsed")
    println("Parsed custom: $parsedCustom")

    // Date arithmetic
    val nextWeek = today.plusWeeks(1)
    val lastMonth = today.minusMonths(1)
    val inFuture = today.plusDays(100)
    println("Next week: $nextWeek")
    println("Last month: $lastMonth")
    println("In 100 days: $inFuture")

    // Duration (time-based) and Period (date-based)
    val duration = Duration.between(
        LocalTime.of(9, 0),
        LocalTime.of(17, 30)
    )
    println("Work day: ${duration.toHours()}h ${duration.toMinutesPart()}m")

    val age = Period.between(birthday, today)
    println("Age: ${age.years} years, ${age.months} months, ${age.days} days")

    // Days between dates
    val daysBetween = ChronoUnit.DAYS.between(birthday, today)
    println("Days alive: $daysBetween")

    // Timezone handling
    val utcNow = ZonedDateTime.now(ZoneId.of("UTC"))
    val tokyoNow = utcNow.withZoneSameInstant(ZoneId.of("Asia/Tokyo"))
    val nyNow = utcNow.withZoneSameInstant(ZoneId.of("America/New_York"))
    println("UTC: $utcNow")
    println("Tokyo: $tokyoNow")
    println("NY: $nyNow")

    // Comparison
    val date1 = LocalDate.of(2024, 1, 1)
    val date2 = LocalDate.of(2024, 12, 31)
    println("Before: ${date1.isBefore(date2)}")
    println("After: ${date1.isAfter(date2)}")
    println("Leap year: ${date1.isLeapYear}")

    // Day of week
    println("Today is: ${today.dayOfWeek}")
    println("Day of year: ${today.dayOfYear}")
}

Use Cases

  • Date formatting for user interfaces
  • Age and duration calculations
  • Timezone conversion for global applications

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.