LocalDateTime and ZonedDateTime in Java

LocalDateTime

LocalDateTime combines LocaleDate and LocalTime together, contains the date and time in the ISO-8601 calendar system without reference to the time zone. Time is stored with nanosecond precision. Contains many convenient methods such as plusMinutes, plusHours, isAfter, toSecondOfDay, etc.

ZonedDateTime

java.time.ZonedDateTime is analogous to java.util.Calendar, the class with the most complete amount of time context information in the ISO-8601 calendar system. It includes a time zone, so this class conducts all operations with time shifts with it in mind.

Get the current date using the Date Time API from Java 8

LocalDate.now();

add 1 week, 1 month, 1 year, 10 years to the current date using the Date Time API

LocalDate.now().plusWeeks(1);
LocalDate.now().plusMonths(1);
LocalDate.now().plusYears(1);
LocalDate.now().plus(1, ChronoUnit.DECADES);

Пet next Tuesday using the Date Time API

LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.TUESDAY));

Get the second Saturday of the current month using the Date Time API

LocalDate
    .of(LocalDate.now().getYear(), LocalDate.now().getMonth(), 1)
    .with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY))
    .with(TemporalAdjusters.next(DayOfWeek.SATURDAY));

Get the current time with millisecond precision using the Date Time API

new Date().toInstant();

Get the current local time with millisecond precision using the Date Time API

LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed