Class DateTimeApiExamples

java.lang.Object
net.jrodolfo.java_evolution.java08.DateTimeApiExamples

public class DateTimeApiExamples extends Object
Demonstrates the Date and Time API introduced in Java 8 under java.time.

Before Java 8, date and time code usually relied on java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat. Those APIs mixed different concepts, were mutable, and made time-zone handling difficult to reason about.

The Java 8 API solves this by giving different time concepts different immutable types. LocalDate represents a date without a time zone, LocalDateTime represents a local date and time, ZonedDateTime adds a zone, Period represents date-based amounts, and Duration represents time-based amounts. The clearer types make many bugs visible in the method signature.

  • Constructor Details

    • DateTimeApiExamples

      public DateTimeApiExamples()
  • Method Details

    • createLocalDate

      public LocalDate createLocalDate(int year, int month, int day)
      Creates a date without a time zone.
      Parameters:
      year - the year
      month - the month from 1 to 12
      day - the day of the month
      Returns:
      the requested local date
    • addDays

      public LocalDate addDays(LocalDate date, long days)
      Adds days to a date, returning a new instance because java.time types are immutable.
      Parameters:
      date - the original date
      days - the number of days to add
      Returns:
      a new date after adding the requested days
    • periodBetween

      public Period periodBetween(LocalDate start, LocalDate end)
      Calculates a date-based amount of time with Period.
      Parameters:
      start - the start date
      end - the end date
      Returns:
      the period between both dates
    • durationBetween

      public Duration durationBetween(LocalDateTime start, LocalDateTime end)
      Calculates a time-based amount of time with Duration.
      Parameters:
      start - the start date-time
      end - the end date-time
      Returns:
      the duration between both date-times
    • formatIsoDate

      public String formatIsoDate(LocalDate date)
      Formats a date with DateTimeFormatter.
      Parameters:
      date - the date to format
      Returns:
      the date formatted as yyyy-MM-dd
    • parseBrazilianDate

      public LocalDate parseBrazilianDate(String text)
      Parses a date using an explicit formatter.
      Parameters:
      text - the date text in dd/MM/yyyy format
      Returns:
      the parsed date
    • createZonedDateTime

      public ZonedDateTime createZonedDateTime(LocalDateTime dateTime, String zoneId)
      Creates a date-time associated with a time zone.
      Parameters:
      dateTime - the local date-time
      zoneId - the zone identifier, such as America/Sao_Paulo
      Returns:
      the zoned date-time