Java 8 new features - time and date API

Keywords: Java

I. time and date

Java 8 provides many new APIs under the java.time package. Here are two more important APIs:

  • Local − simplifies the processing of date and time, without the problem of time zone.
  • Zone − processes the date and time through a defined time zone.

II. Localization time and date API

The LocalDate, LocalTime, and LocalDateTime classes can handle situations without time zone issues

  • Get local time
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.now();
LocalTime localTime = LocalTime.now();
System.out.println(localDate);
System.out.println(localDateTime);
System.out.println(localTime);
//Output: November 3, 2018
//2018-11-03T11:48:53.609
//11:48:53.609
  • Action on time
LocalDateTime localDateTime = LocalDateTime.now();
//Increase for 5 years
LocalDateTime localDateTime1 = localDateTime.plusYears(5);
System.out.println(localDateTime1);
//Decrease by 4 months
LocalDateTime localDateTime2 = localDateTime.minusMonths(4);
System.out.println(localDateTime2);
//Get month
int monthValue = localDateTime.getMonthValue();
System.out.println(monthValue);
//Acquisition week
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
System.out.println(dayOfWeek);
//Year of acquisition
int year = localDateTime.getYear();
System.out.println(year);

//2023-11-03T15:10:52.405
//2018-07-03T15:10:52.405
//11
//SATURDAY
//2018
  • Computation interval

Duration: calculate the interval between two times

LocalDateTime localDateTime = LocalDateTime.now();
Thread.sleep(500);
LocalDateTime localDateTime1 = LocalDateTime.now();
Duration duration = Duration.between(localDateTime,localDateTime1);
System.out.println(duration.toMillis());
//Output: 505

Period: calculate the interval between two dates

LocalDate localDate = LocalDate.now();
LocalDate localDate1 = LocalDate.of(2008,8,8);
Period period = Period.between(localDate1,localDate);
System.out.println(period.getYears()+":"+period.getMonths()+":"+period.getDays());
//Output: 10:2:26
  • Format time or date
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-mm-dd:hh:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
String format = dateTimeFormatter.format(localDateTime);
System.out.println(format);
//Output: 2018-44-03:03:44:22

III. time and date API in time zone

//Get the time with the time zone of Europe/Paris
LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Europe/Paris"));
System.out.println(localDateTime);
//Combining a date with a time zone
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Europe/Paris"));
System.out.println(zonedDateTime);
//Get current time zone
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId);

//Output: 2018-11-03T08:51:34.629
//2018-11-03T08:51:34.629+01:00[Europe/Paris]
//Asia/Shanghai

Posted by asuperstar103 on Tue, 10 Dec 2019 14:17:48 -0800