Date and Time API - JSR 310 - Need for the enhancement
Anybody who has worked with Java date, calendar and time prior to java8 has had to google at least a few times before their code worked fine. that was how tedious or non-intuitive the entire code surrouding the date and time model was.
Secondly, the objects related to date time were all mutable, causing issues in multithreaded functionalities. (classic example use of SimpleDateFormat.parse()).
Third, missing common operations like finding time in TZ x knowing current time in TZ y, month, day, year operations on date etc.
Updates in java8
Completely new model of date and time based on the calendar system defined in ISO-8601. java.time.* package
Two types of times:
- human time (LocalDate, LocalTime, LocalDateTime, ZonedDateTime,Period)
- continuous time / unix timestamp (Instant, duration)
One can implement their own calendar system by extending the ChronoLocalDate.
Sample code
Ease of doing date manipulations:
//code to print next Friday LocalDate today= LocalDate.now(); System.out.println(today.plusWeeks(1).with(TemporalAdjusters.next(DayOfWeek.FRIDAY)));
Ease of doing formatting
LocalDateTime now = LocalDateTime.now();
System.out.println(now.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
Ease of date parsingLocalDate d3 = LocalDate.parse("18/07/2017",DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(d3);
Ease of period /duration between 2 dates:
LocalDate travelDate=LocalDate.of(2015, Month.NOVEMBER, 21);
LocalDate returnDate = LocalDate.now();
Period travelPeriod = Period.between(travelDate, returnDate);
System.out.println("You were travelling for a period of "+travelPeriod.getYears()+" years and "+travelPeriod.getMonths()+ " months and "+travelPeriod.getDays()+" days ( total of "+ChronoUnit.DAYS.between(travelDate, returnDate)+" days)");