Java OffsetTime
The Java OffsetTime class is an immutable and thread-safe class that represents a time, in the format of hour-minute-second-offset.
How to use
The OffsetTime class can be used to store all time fields, to a precision of nanoseconds, as well as a zone offset. For example, the value “10:30.20.123456789+02:00” can be stored in an OffsetTime. Try the following examples to better understand –
Now example
The following example program shows how you can create an instance of OffsetTime and get the current time.
import java.time.OffsetTime; import java.time.temporal.ChronoField; public class OffsetTimeExample1 { public static void main(String[] args) { // Create instance of OffsetTime OffsetTime offset = OffsetTime.now(); // Print local time System.out.println(offset); } }
Different fields example
The following example program shows how you can get different fields from OffsetTime.
import java.time.OffsetTime; import java.time.temporal.ChronoField; public class OffsetTimeExample2 { public static void main(String[] args) { // Create instance of OffsetTime OffsetTime offset = OffsetTime.now(); // Get hour of day field int hour = offset.get(ChronoField.HOUR_OF_DAY); System.out.println(hour); // Get minute of day field int minute = offset.get(ChronoField.MINUTE_OF_DAY); System.out.println(minute); // Get second of day field int second = offset.get(ChronoField.SECOND_OF_DAY); System.out.println(second); } }
Format example
The following example program shows how you can format and print time.
import java.time.OffsetTime; import java.time.format.DateTimeFormatter; public class OffsetTimeExample3 { public static void main(String[] args) { // Create instance of OffsetTime OffsetTime offset = OffsetTime.now(); // Create formatter DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); System.out.println(offset.format(formatter)); } }