Java OffsetDateTime
The Java Instant class is an immutable and thread-safe class that represents an immutable date-time with an offset. The OffsetDateTime class can be used to store all date and time fields, For example, the value “22nd April 2019 at 10:20.30.123456789 +02:00” can be stored in an OffsetDateTime.
How to use
The OffsetDateTime class can be used when modeling date-time concepts in more details, or when communicating to a database or in a network protocol. Try the following examples to better understand –
Now example
The following example program shows how you can create an instance of OffsetDateTime and get the current date and time.
import java.time.OffsetDateTime; public class OffsetDateTimeExample1 { public static void main(String[] args) { // Create instance of OffsetDateTime OffsetDateTime offsetDateTime = OffsetDateTime.now(); // Print local time System.out.println(offsetDateTime.toLocalTime()); } }
Add/Subtract example
The following example program shows how you can plus/minus days in OffsetDateTime.
import java.time.OffsetDateTime; public class OffsetDateTimeExample2 { public static void main(String[] args) { // Create instance of OffsetDateTime OffsetDateTime offsetDateTime = OffsetDateTime.now(); System.out.println("Current: " + offsetDateTime.toLocalDate()); // Add 5 days offsetDateTime = OffsetDateTime.now().plusDays(5); System.out.println("Plus 5 day: " + offsetDateTime.toLocalDate()); // Subtract 5 days offsetDateTime = OffsetDateTime.now().minusDays(5); System.out.println("Minus 5 day: " + offsetDateTime.toLocalDate()); } }
Format example
The following example program shows how you can format date and time.
import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; public class OffsetDateTimeExample3 { public static void main(String[] args) { // Create instance of OffsetDateTime OffsetDateTime offsetDateTime = OffsetDateTime.now(); // Format date and time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy"); String format = offsetDateTime.format(formatter); System.out.println(format); } }