Java LocalTime Class: Current Time, Formatting and Methods - Quiz

Total: 12 questions

1. 

What is LocalTime in Java and how is it different from LocalDateTime, ZonedDateTime and Instant?

java.time.LocalTime is an immutable, thread-safe class from Java 8 that stores only a time of day (hours, minutes, seconds, nanoseconds) with no date and no time zone, for example 13:45:30.123456789. It fits schedules, opening hours and alarms.

LocalDateTime adds a date to the time, ZonedDateTime adds a time zone as well, and Instant is an exact point on the UTC timeline (timestamps, logs). You turn a LocalTime into a LocalDateTime with atDate(LocalDate) and go back with toLocalTime(); to get an Instant you also need a zone: time.atDate(date).atZone(zone).toInstant().

2. 

How do you get the current time in Java with LocalTime, and how do you make such code testable?

LocalTime.now() returns the time of day from the system clock in the JVM default time zone, including fractions of a second (since Java 9, typically microseconds). For another zone use LocalTime.now(ZoneId.of("Asia/Tokyo")). When you show the time to a user, format it or truncate it: LocalTime.now().truncatedTo(ChronoUnit.SECONDS).

For tests, pass a Clock into the class and call LocalTime.now(clock): in production use Clock.systemDefaultZone(), in a test use Clock.fixed(Instant.parse("2024-03-15T10:00:00Z"), ZoneOffset.UTC), and the result is always 10:00.

3. 

What constants does LocalTime have, and what are the bounds of a time of day?

LocalTime has four constants: MIN and MIDNIGHT are the start of the day, 00:00 (equal values, LocalTime.MIN.equals(LocalTime.MIDNIGHT) returns true), NOON is 12:00, and MAX is the last nanosecond of the day, 23:59:59.999999999.

There is no "24:00": LocalTime.of(24, 0) throws DateTimeException. The same bound shows up in seconds since midnight: toSecondOfDay() returns 0 to 86399 (LocalTime.MAX gives 86399 because fractions of a second are dropped), and LocalTime.ofSecondOfDay(86400) throws DateTimeException. For the upper bound of an "until end of day" range, use LocalTime.MAX.

4. 

How do you compare two LocalTime values and check whether a time falls into a range, including a range across midnight?

For order use isBefore() and isAfter() (strictly earlier / strictly later); for equality use equals(), not ==, which compares references. compareTo() returns a negative number, 0 or a positive number, so LocalTime values can be sorted. For example, LocalTime.of(12, 0).equals(LocalTime.NOON) is true.

A regular range (9:00–18:00): !t.isBefore(from) && t.isBefore(to). When the range crosses midnight (22:00–06:00), the start is later than the end, so t.isAfter(from) && t.isBefore(to) is always false. You need "or": t.isAfter(from) || t.isBefore(to) — for 02:00 this gives true.

5. 

What is the difference between the with...() methods and truncatedTo() in LocalTime?

withHour(), withMinute(), withSecond(), withNano() and with(ChronoField, long) replace one field and keep the others: LocalTime.of(13, 45, 30).withHour(8) gives 08:45:30. An out-of-range value (withHour(25)) throws DateTimeException.

truncatedTo(ChronoUnit) zeroes every field smaller than the given unit: for 13:45:30.123456789, truncatedTo(ChronoUnit.MINUTES) returns 13:45. This is handy for comparing now() values "to the minute". Units longer than a day (MONTHS, YEARS) throw UnsupportedTemporalTypeException. Neither method changes the original object — both return a new one.

6. 

What is the difference between LocalTime.now() and System.nanoTime(), and which one should you use to measure how fast code runs?

LocalTime.now() answers "what time is it?" — the time of day from the system clock. System.nanoTime() answers "how much time has passed?": it returns a long number of nanoseconds from an arbitrary origin; the number itself has nothing to do with the time of day and only makes sense as the difference between two calls.

To measure how fast code runs, use System.nanoTime(): its readings do not depend on adjustments of the system clock (manual changes, NTP sync). The difference between two LocalTime.now() calls can even be negative if the clock was set back or the measurement crossed midnight.

7. 

What is the difference between Duration and Period in Java, and when should you use each?

Duration stores exact physical time in seconds (long) and nanoseconds (int): a day is exactly 86,400 seconds, and toString() looks like PT1H30M. Period stores a calendar amount in years, months and days (P1Y2M3D): a month lasts 28–31 days, and a day lasts 23 or 25 hours when the clocks change.

ZonedDateTime base = ZonedDateTime.of(2024, 3, 30, 12, 0, 0, 0, ZoneId.of("Europe/Berlin"));
base.plus(Period.ofDays(1));   // 2024-03-31T12:00+02:00[Europe/Berlin]
base.plus(Duration.ofDays(1)); // 2024-03-31T13:00+02:00[Europe/Berlin]

Period keeps the wall-clock time, Duration adds exactly 24 hours. Both classes implement TemporalAmount, and both are immutable and thread-safe. Use Duration for timeouts and execution time, and Period for age, subscription terms and «in 2 months».

8. 

How do you create a Duration and a Period, and why is Duration.ofDays(1) printed as PT24H?

The classes have no constructors; objects are created with the static of*() methods:

Duration.ofDays(1);                  // PT24H
Duration.ofSeconds(1, 1_000_000_000); // PT2S
Duration.ofMillis(1500);             // PT1.5S
Duration.of(1, ChronoUnit.MONTHS);   // UnsupportedTemporalTypeException: Unit must not have an estimated duration

Period.of(5, 4, 3);   // P5Y4M3D
Period.ofWeeks(2);    // P14D
Period.of(0, 14, 40); // P14M40D

Internally a Duration stores only seconds and nanoseconds, so toString() never shows days. Duration.of() accepts only units with an exact length (from NANOS to DAYS). A Period has no weeks (ofWeeks(2) immediately becomes 14 days), and its values are not normalized. The zero values are Duration.ZERO and Period.ZERO.

9. 

How do you format a Duration as hh:mm:ss?

There is no built-in formatter for Duration, and DateTimeFormatter does not work with amounts of time. Build the string from parts:

Duration d = Duration.ofSeconds(9030);
// Java 9+
String.format("%02d:%02d:%02d", d.toHours(), d.toMinutesPart(), d.toSecondsPart()); // 02:30:30
// Java 8
String.format("%02d:%02d:%02d", d.toHours(), d.toMinutes() % 60, d.getSeconds() % 60); // 02:30:30

The to*() methods convert the whole duration into one unit (getSeconds() returns 9030, not 30), while the to*Part() methods return a single part. The LocalTime.MIDNIGHT.plus(d) trick works only for durations shorter than a day: for 100,000 seconds it shows 03:46:40 instead of 27:46:40.

10. 

How do you compare two Durations, and why does Period.ofMonths(12).equals(Period.ofYears(1)) return false?

Duration implements Comparable<Duration>: it has equals(), compareTo() (compare the result with zero), isZero(), isNegative() and, since Java 18, isPositive(). Two durations are equal when their total seconds and nanoseconds match:

Duration.ofHours(1).equals(Duration.ofMinutes(60));                // true
Period.ofMonths(12).equals(Period.ofYears(1));                      // false
Period.ofMonths(12).normalized().equals(Period.ofYears(1));         // true

Period.equals() compares years, months and days one by one. normalized() turns months above 12 into years (days are left alone), and toTotalMonths() returns the total number of months. Period has no compareTo(): without a reference date you cannot say which is longer — 1 month or 30 days.

11. 

How do you calculate age with Period.between, and why does getDays() not return the total number of days?

Period.between(start, end) takes two LocalDate values and returns the difference as «N years, M months, K days»: full months are counted first, then the remaining days; the end date is exclusive.

Period age = Period.between(LocalDate.of(1990, 8, 25), LocalDate.of(2024, 3, 15));
System.out.println(age);            // P33Y6M19D
System.out.println(age.getYears()); // 33

LocalDate start = LocalDate.of(2024, 1, 31);
LocalDate end = LocalDate.of(2024, 3, 1);
Period.between(start, end).getDays();   // 1 (the period is P1M1D)
ChronoUnit.DAYS.between(start, end);    // 30

getDays() returns only the leftover days after the full months. If you need a single number — total days, months or years — use ChronoUnit.DAYS.between(), ChronoUnit.MONTHS.between() or ChronoUnit.YEARS.between(). For a LocalDateTime, call toLocalDate() first.

12. 

In what format are Duration and Period printed and parsed by parse()?

Both classes use ISO-8601. A Duration is PT + hours H, minutes M, seconds S; a Period is P + years Y, months M, weeks W, days D. The letter T separates the time part: P1M is a month, PT1M is a minute.

Duration.parse("PT90M");   // PT1H30M
Duration.parse("P2DT3H");  // PT51H
Period.parse("P1Y2W3D");   // P1Y17D
Duration.parse("1:30");    // DateTimeParseException
Period.parse("PT1H");      // DateTimeParseException

Duration.parse() accepts days but converts them into 24-hour blocks. Years and months are not allowed in a Duration, and time is not allowed in a Period. Parse a string like «01:30» manually: split(":"), then Duration.ofHours(h).plusMinutes(m).

Page 1 of 1