Reasons for new Date API in Java8
Thread Safety: Date & Calendar classs are not thread safe, hence developers had to deal with complexity of debugging concurrency issues or handle thread safety in code. Whereas new Date & Time APIs in java8 are immutable & thread safe.
Ease of understanding: Date & Calendar classs are not designed well, that is, for doing day to day date operations there are no adequate methods. New Date & Time APIs follows consistent models of date, time, duration & period providing variety of utility methods for date calculations.
Zoned Date & Time: For handling date time zones, developers had to write additional logic in the code. New Date & Time APIs hae Zoned Date & Time APIs. It provides 601 different time zones and zoneId represents these zones as shown in below examples
A TemporalAmount represents an amount of time, which may be date-based or time-based, which this factory extracts to a Period.
Compatibility with Date and Calendar: In order to convert existing Date and Calendar from Java 7 (or earleir), Java 8 has provided toInstant method as follows
In earlier Java versions, ThreeTen & Joda-Time libraries can provide the similar capabilities as that Java8. Using these libraries will make migration in future easier.
Below are a few important classes from new Date & Time APIs from Java8
package java8.datetimeapi;
import java.time.*;
import java.time.temporal.*;
import java.util.*;
import java.time.format.DateTimeFormatter;
import java.util.stream.Collectors;
public class DateTimeAPIDemo {
public static void main(String[] args) {
System.out.println("-------------LOCAL DATE Examples--------------");
System.out.println("Create instance using .now() :"+LocalDate.now());
System.out.println("Create instance using .of() :"+LocalDate.of(2021, 8, 16));
System.out.println("Create instance using .of() :"+LocalDate.of(2021, Month.AUGUST, 16));
System.out.println("Create instance using .parse() :"+LocalDate.parse("2021-08-16"));
System.out.println("Adding a day :"+LocalDate.now().plusDays(1));
System.out.println("Minus month :"+LocalDate.now().minusMonths(1));
System.out.println("Minus month ChronoUnit :"+LocalDate.now().minus(1, ChronoUnit.MONTHS));
System.out.println("Day of week :"+LocalDate.now().getDayOfWeek());
System.out.println("Day of month Integer :"+LocalDate.now().getDayOfMonth());
System.out.println("Local Date compareTo :"+ LocalDate.now().compareTo(LocalDate.of(2025, 01, 01)));
System.out.println("Local Date isBefore :"+LocalDate.now().isBefore(LocalDate.of(2025, 01, 01)));
System.out.println("Local Date isAfter :"+LocalDate.now().isAfter(LocalDate.of(2025, 01, 01)));
System.out.println("Days untill 2025-01-01 :"+LocalDate.now().until(LocalDate.of(2025, 01, 01), ChronoUnit.DAYS));
System.out.println("Dates between 15-Aug to 20-Aug :"+LocalDate.of(2021, 8, 15).datesUntil(LocalDate.of(2021, 8, 20)).collect(Collectors.toList()));
System.out.println("Dates bet 15 to 20 with step=2 :"+LocalDate.of(2021, 8, 15).datesUntil(LocalDate.of(2021, 8, 20),Period.ofDays(2)).collect(Collectors.toList()));
System.out.println("Is leap year? :"+LocalDate.now().isLeapYear());
System.out.println("Length of Month :"+LocalDate.now().lengthOfMonth());
System.out.println("At Start of this Day :"+LocalDate.now().atStartOfDay());
System.out.println("-------------LOCAL TIME Examples--------------");
System.out.println("Create instance using .now() :"+LocalTime.now());
System.out.println("Create instance using .of() :"+LocalTime.of(15, 31, 23));
System.out.println("Local Time compareTo :"+LocalTime.of(15, 21, 15).compareTo(LocalTime.of(15, 31, 24)));
System.out.println("Seconds until :"+LocalTime.of(15, 21, 15).until(LocalTime.of(15, 31, 25), ChronoUnit.SECONDS));
System.out.println("Local Time isBefore :"+LocalTime.of(15, 21, 15).isBefore(LocalTime.of(15, 31, 25)));
System.out.println("Local Time isAfter :"+LocalTime.of(15, 21, 15).isAfter(LocalTime.of(15, 31, 25)));
System.out.println("Current time - 600 seconds :"+LocalTime.now().minus(600, ChronoUnit.SECONDS));
System.out.println("Current time - 600 seconds :"+LocalTime.now().plus(600, ChronoUnit.SECONDS));
System.out.println("Query using TemporalQueries :"+LocalTime.now().query(TemporalQueries.precision()));
System.out.println("Query using Customized query :"+LocalTime.now().query(EarlyMorningHoursQuery));
System.out.println("-------------LOCAL DATE TIME Examples--------------");
System.out.println("Create instance using .now() :"+LocalDateTime.now());
System.out.println("Create instance using .parse :"+LocalDateTime.parse("2021-08-16T16:45:34"));
System.out.println("Using LocalDate & LocalTime :"+LocalDateTime.of(LocalDate.now(), LocalTime.now()));
System.out.println("LocalDateTime compareTo :"+LocalDateTime.now().compareTo(LocalDateTime.of(LocalDate.of(2022, 8, 16), LocalTime.of(16, 30))));
System.out.println("Days Until 16-08-2022 16:30 :"+LocalDateTime.now().until(LocalDateTime.of(LocalDate.of(2025, 8, 16), LocalTime.of(16, 30)), ChronoUnit.DAYS));
System.out.println("-------------ZONE DATE TIME Examples--------------");
System.out.println("Using localDateTime & zoneId :"+ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Asia/Kolkata")));
System.out.println("Using .parse() :"+ZonedDateTime.parse("2021-08-16T16:45:34+05:30[Europe/Paris]"));
System.out.println("Zone Id of Asia-Kolkata is :"+ZoneId.of("Asia/Kolkata"));
System.out.println("System defualt zone Id :"+ZoneId.systemDefault());
System.out.println("Local time with offset :"+OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.of("+02:00")));
ZoneId.getAvailableZoneIds().stream().forEach(a-> System.out.println("Zone: "+a));
System.out.println("-------------PERIOD Examples--------------");
System.out.println("Adding 5 days to current date :"+LocalDate.now().plus(Period.ofDays(5)));
System.out.println("Period between in Days :"+Period.between(LocalDate.of(2021, 8, 16), LocalDate.of(2021, 4, 13)).getDays());
System.out.println("Period from() :"+Period.from(Period.ofYears(2)));
Period pr = Period.parse("P10Y-2M5D");
System.out.println("Period parse() :"+ pr.getYears()+" Years, "+pr.getMonths()+" Months and "+pr.getDays()+" Days");
System.out.println("Period multipliedBy :"+ pr.multipliedBy(2));
System.out.println("Period negated :"+pr.negated());
System.out.println("Period normalized 17M to 1Y & 5M:"+ Period.of(10, 17, 20).normalized());
System.out.println("Period totalMonths :"+pr.toTotalMonths());
System.out.println("-------------DURATION Examples--------------");
Duration dr = Duration.of(30, ChronoUnit.MINUTES);
System.out.println("Duration compareTo :"+dr.compareTo(Duration.of(10, ChronoUnit.SECONDS)));
System.out.println("Duration dividedBy :"+dr.dividedBy(10));
System.out.println("Duration addTo :"+dr.addTo(LocalDateTime.now()));
System.out.println("Duration abs :"+dr.abs());
System.out.println("-------------Compatibility Examples--------------");
Date date = new Date();
System.out.println("Conver Date to LocalDate :"+LocalDateTime.ofInstant(date.toInstant(), ZoneId.of("Asia/Kolkata")));
Calendar cal = Calendar.getInstance();
System.out.println("Conver Calendar to LocalDate :"+LocalDateTime.ofInstant(cal.toInstant(), ZoneId.of("Asia/Kolkata")));
System.out.println("-------------Formatting Examples--------------");
LocalDateTime ldt = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("Current LocalDateTime :"+ldt);
System.out.println("Format in ISO Date Time :"+ldt.format(DateTimeFormatter.ISO_DATE_TIME));
System.out.println("Format pattern & locale :"+ldt.format(DateTimeFormatter.ofPattern("dd-MM-yyyy").withLocale(Locale.GERMANY)));
System.out.println("Format pattern & locale :"+ldt.format(DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.US)));
}
private static final TemporalQuery<Boolean> EarlyMorningHoursQuery =
temporal -> {
LocalTime lt = LocalTime.from(temporal);
return (lt.compareTo(LocalTime.of(5, 0)) >=0 && (lt.compareTo(LocalTime.of(8, 0)) <0));
};
}
No comments:
Post a Comment