LocalTime

suggest change

To use just the time of day, use LocalTime. You can instantiate a LocalTime object in several ways:

  1. LocalTime time = LocalTime.now();
  2. time = LocalTime.MIDNIGHT;
  3. time = LocalTime.NOON;
  4. time = LocalTime.of(12, 12, 45);

LocalTime also has a built-in toString method that displays the format very nicely.

System.out.println(time);

You can also get, add, and subtract hours, minutes, seconds, and nanoseconds. plusMinutes and minusMinutes return a new LocalTime; these calls do not change time:

time.plusMinutes(1);
time.getMinutes();
time.minusMinutes(1);

You can turn it into a Date object with the following code:

LocalTime lTime = LocalTime.now();
Instant instant = lTime.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
        atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);

This class works very nicely within a timer class to simulate an alarm clock.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents