Java8 – Date and Time examples

javabullets
17.4K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content