scalabeginner

Date and Time Operations

Work with dates and times using Java Time API: parsing, formatting, arithmetic, and time zones.

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

@main def run(): Unit =
  // Current date/time
  val now = LocalDateTime.now()
  val today = LocalDate.now()
  val currentTime = LocalTime.now()
  val instant = Instant.now()

  println(s"Now: $now")
  println(s"Today: $today")
  println(s"Time: $currentTime")
  println(s"Instant: $instant")

  // Create specific dates
  val date = LocalDate.of(2024, 6, 15)
  val time = LocalTime.of(14, 30, 0)
  val dateTime = LocalDateTime.of(date, time)
  println(s"\nSpecific: $dateTime")

  // Formatting
  val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
  val isoFormat = DateTimeFormatter.ISO_LOCAL_DATE_TIME
  println(s"Formatted: ${dateTime.format(formatter)}")
  println(s"ISO: ${dateTime.format(isoFormat)}")

  // Parsing
  val parsed = LocalDate.parse("2024-06-15")
  val parsedDT = LocalDateTime.parse("2024-06-15T14:30:00")
  val custom = LocalDate.parse("15/06/2024", DateTimeFormatter.ofPattern("dd/MM/yyyy"))
  println(s"\nParsed: $parsed, $custom")

  // Arithmetic
  val tomorrow = today.plusDays(1)
  val nextWeek = today.plusWeeks(1)
  val lastMonth = today.minusMonths(1)
  val inTwoHours = LocalTime.now().plusHours(2)
  println(s"\nTomorrow: $tomorrow")
  println(s"Next week: $nextWeek")
  println(s"Last month: $lastMonth")

  // Duration and Period
  val start = LocalDate.of(2024, 1, 1)
  val end = LocalDate.of(2024, 12, 31)
  val period = Period.between(start, end)
  val days = ChronoUnit.DAYS.between(start, end)
  println(s"\nPeriod: ${period.getMonths} months, ${period.getDays} days")
  println(s"Total days: $days")

  // Time zones
  val nyTime = ZonedDateTime.now(ZoneId.of("America/New_York"))
  val tokyoTime = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"))
  val utcTime = ZonedDateTime.now(ZoneId.of("UTC"))
  println(s"\nNY: ${nyTime.format(formatter)}")
  println(s"Tokyo: ${tokyoTime.format(formatter)}")
  println(s"UTC: ${utcTime.format(formatter)}")

  // Convert between zones
  val nyToTokyo = nyTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"))
  println(s"NY in Tokyo: ${nyToTokyo.format(formatter)}")

  // Comparison
  val d1 = LocalDate.of(2024, 6, 1)
  val d2 = LocalDate.of(2024, 6, 15)
  println(s"\n$d1 before $d2: ${d1.isBefore(d2)}")
  println(s"$d1 after $d2: ${d1.isAfter(d2)}")

  // Day of week, month info
  println(s"\nDay of week: ${today.getDayOfWeek}")
  println(s"Day of year: ${today.getDayOfYear}")
  println(s"Is leap year: ${today.isLeapYear}")
  println(s"Month length: ${today.lengthOfMonth()} days")

Use Cases

  • Date arithmetic and comparison
  • Time zone conversions
  • Date formatting and parsing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.