Skip to content

Instantly share code, notes, and snippets.

@rmg007
Created October 21, 2022 11:55
Show Gist options
  • Save rmg007/0cc9ef8c2de19273a6b7d72096a0f563 to your computer and use it in GitHub Desktop.
Save rmg007/0cc9ef8c2de19273a6b7d72096a0f563 to your computer and use it in GitHub Desktop.
Local Time Example
import java.time.Duration;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
public class LocalTimeExample {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println("now: " + now);
LocalTime workStart = LocalTime.parse("08:00");
System.out.println("work start: " + workStart);
LocalTime workEnd = LocalTime.of(16, 0);
System.out.println("work end: " + workEnd);
System.out.println(now.getHour());
System.out.println(now.getMinute());
System.out.println(now.getSecond());
System.out.println(now.get(ChronoField.AMPM_OF_DAY)); // 0: AM, 1: PM
System.out.println(LocalTime.MIN);
System.out.println(LocalTime.MAX);
// calculating difference between times
System.out.println("Working hours: " + (workStart.until(workEnd, ChronoUnit.HOURS)));
System.out.println("Working hours: " + ChronoUnit.HOURS.between(workStart, workEnd));
System.out.println("Working hours: " + Duration.between(workStart, workEnd));
// plus and minus methods
now.plus(1, ChronoUnit.HOURS);
now.plusHours(1);
now.plusMinutes(5);
// before and after methods
boolean isBefore = LocalTime.parse("09:40").isBefore(LocalTime.parse("09:35"));
System.out.println(isBefore);
System.out.println(now.truncatedTo(ChronoUnit.HOURS));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment