Learnitweb

java.time package in Java 8 – Introduction

java.time package was introduced in Java 8 as a better way of dealing with date and time. java.util.Date and java.util.Calendar classes were not convenient to use and also didn’t handle internationalization and localization situations very well.

java.util.Date, java.util.Calendar, and java.text.DateFormat classes which we were using for so many years are still there but java.time package is designed to replace these classes.

Following are the important classes of java.time package:

Without time-zone

  • java.time.LocalDate : This class represents a date without a time or time-zone in the ISO-8601 calendar system. This class is immutable and thread safe.
  • java.time.LocalTime : This class represents a time without a date or time-zone in the ISO-8601 calendar system. Time is represented to nanosecond precision. This class is immutable and thread safe.
  • java.time.LocalDateTime : This class represents a date-time without a time-zone in the ISO-8601 calendar system. This class is immutable and thread-safe.

With time-zone

  • java.time.ZonedDateTime : This class represents a date-time with a time-zone in the ISO-8601 calendar system. This class is immutable and thread safe.
  • java.time.OffsetDateTime : This class represents a a date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system. This class is immutable and thread safe.

Formatter for date and time

  • java.time.format.DateTimeFormatter : This class is used for parsing date-time objects. This class provides two important methods, format(DateTimeFormatter formatter) and parse(CharSequence text, DateTimeFormatter formatter). This class is immutable and thread-safe.

Periods, Durations, and Instants

  • java.time.Periods : This class represents a quantity or amount of time in terms of years, months and days.
  • java.time.Duration : This class represents a quantity or amount of time in terms of seconds and nanoseconds.
  • java.time.Instant : This class represents a specific instant in time. This class can be used when you want to compute the duration between two instants. This class can also be used to record event time-stamps in the application.

Date and time adjustments

  • java.time.temporal.TemporalAdjusters : This class contains a set of adjusters. Adjusters are provided as static methods. Few of the adjusters provided by this class are :
    • finding the day-of-week in month
    • finding the first day and last day of month
    • finding the first day of next month
    • finding the first of the next year
    • finding first day and last day of year
    • finding the next or previous day-of-week
  • java.time.temporal.ChronoUnit : A standard set of date periods units like DAYS, HOURS, MINUTES, MONTHS, SECONDS, YEARS. This is a final, immutable and thread-safe enum.