8. Java 8: Use Java SE8 Date/Time API Flashcards
True/False
The new date/time API is not thread-safe because it resulted in performance problems in the past.
False
The new API is thread-safe and all objects are immutable (just like a String). This was the main problem with the old date / Calendar API.
What are the 4 ways a Instant object be created?
Instant.now()
Instant.ofEpochSecond(999999)
Instant.ofEpochMilli(99999L)
Instant.parse(“2015-07-10T12:00:00Z”)
How can you get the EPOCH in seconds from a instant object?
instant.getEpochSecond();
How can you get the EPOCH in milliseconds from a instant object?
instant.getEpochMilli();
What are the 3 ways to create a LocalDate object?
LocalDate.now();
LocalDate.of(1979, Month.FEBRUARY, 15);
LocalDate.ofYearDay(2015,256)
What are the 4 ways of creating a LocalTime object?
LocalTime.now()
LocalTime.of(12, 0) // 12:00
LocalTime.of(13,33,45) // 13:33:45
LocalTime.ofSecondOfDay(121) // 12:02:01
Name 2 ways of creating a LocalDateTime object?
LocalDateTime.now();
LocalDateTime.of(2015, 12, 31, 13, 45); //2015-12-31 13:45
What is the difference between a LocalDateTime object and a ZonedDateTime object?
ZonedDateTime contains timezone information.
How would one create a ZonedDateTime object using the current time and the timezone of Europe/Berlin? And a ZonedDateTime using a offset of 3 hours from GMT?
ZoneId zoneIdBerlin = ZoneId.of(“Europe/Berlin”);
ZoneId zoneIdOffset = ZoneId.offOffset(“GMT”, ZoneOffset.ofHours(“+3”));
LocalDateTime now = LocalDateTime.now();
ZonedDateTime berlin = ZonedDateTime.of(now, zoneIdBerlin);
ZonedDateTime plus3 = berlin.withZoneSameInstant(zonedIdOffset);
Use the Period class to print the amount of years, months and days that two dates are apart.
LocalDate d1 = LocalDate.of(2015,1,1)
LocalDate d2 = LocalDate.of(2017,2,15)
Period period = Period.between(d1,d2);
System.out.println(period.getYears()); // 2
System.out.println(period.getMonths()); // 1
System.out.println(period.getDays()); // 14
Use the ChronoUnit class to calculate the total amount of days between two dates.
LocalDate d1 = LocalDate.of(2017, 1, 1);
LocalDate d2 = LocalDate.of(2017,2,1);
ChronoUnit.DAYS.between(d1, d2);
How can you create Instant of the current time?
Instant.now();
What is the result of the following code:
Instant i1 = Instant.now();
Thread.sleep(1000);
Instant i2 = Instant.now();
System.out.println(Duration.between(i1,i2).getSeconds());
System.out.println(Duration.between(i2,i1).getSeconds());
1
-1
Given two Instant objects (i1, i2) how would one get the number of nano seconds between those Instants?
Duration.between(i1, i2).toNanos();
How to format a LocalDateTime object to the pattern “ yyyy-MM-dd”?
date.format(DateTimeFormatter.ofPattern(“yyyy-MM-dd”));