Back
Close

Java8 – Date and Time examples

javabullets
17K views

Java8 – Date and Time examples

This post originally appeared in my blog, www.javabullets.com as part of a series covering Java8 features.

We had two date implementations before Java8 – java.util.Date and java.util.Calendar. There were numerous issues with these implementations which Java8 seeks to resolve with its new java.time API.

Issues

  • API Design – java.util.Date and java.util.Calendar both had issues including -
    • months starting from 0
    • in the case of Date year starting from 1900
    • Date also represented a point in time, seconds from the epoch, while its toString method included a TimeZone
    • No single class representing Time or Date
  • DateFormat not thread safe

Joda-Time evolved as a defacto standard for Java dates, and its lead developer Stephen Colebourne defined the Java8 JSR-310 API.

Pre-Java8 Date and Calendar Examples

The following snippet demonstrates -

  • toString method contains a Timezone
  • Date - Month Starts at zero, and year at 1900
  • Calendar - Month still starts at zeron, but the year is now fixed

Note this will generate a deprecated API warning

New Features

  1. New package – java.time.*
  2. Core Classes – LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration, Instant
  3. Immutable
  4. Factory methods

LocalDate And LocalTime Examples

The following snippet demonstrates -

  • LocalDate - Date without Timezone
  • LocalTime - Time without Timezone

LocalDateTime Examples

  • Combines LocalDate and LocalTime
  • Called through factory methods of, now, parse
  • Immutable
  • No TimeZone

ZonedDateTime

  • Associate DateTime with TimeZone

CustomAdjuster

  • The adjuster will adjust a date according to the defined rule

Period Or Duration

  • Period - Duration in day, weeks, month, years
  • Duration - days, hours, minutes, seconds

If you have liked this post, check out my personal blog which contains similar tutorials at www.javabullets.com

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io