Home »
Java »
Java Reference »
Java Instant Class
Java Instant Class | atOffset() Method with Example
Instant Class atOffset() method: Here, we are going to learn about the atOffset() method of Instant Class with its syntax and example.
Submitted by Preeti Jain, on May 21, 2020
Instant Class atOffset() method
- atOffset() method is available in java.time package.
- atOffset() method is used to returns OffsetDateTime to merge this Instant with the given zone offset.
- atOffset() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- atOffset() method may throw an exception at the time of representing Instant.
DateTimeException: This exception may throw when the given parameter couldn’t adjust this Instant.
Syntax:
public OffsetDateTime atOffset(ZoneOffset off);
Parameter(s):
- ZoneOffset off – represents the zone offset to merge with this Instant.
Return value:
The return type of this method is OffsetDateTime, it returns OffsetDateTime object that holds the value merged this Instant with the given offset.
Example:
// Java program to demonstrate the example
// of atOffset(ZoneOffset off) method
// of Instant
import java.time.*;
public class AtOffsetOfInstant {
public static void main(String args[]) {
// Instantiates two Instant ,
// two ZoneOffset
Instant ins1 = Instant.parse("2006-04-03T05:10:15.00Z");
Instant ins2 = Instant.parse("2007-06-05T10:20:30.00Z");
ZoneOffset zo_off1 = ZoneOffset.ofTotalSeconds(10);
ZoneOffset zo_off2 = ZoneOffset.ofHours(2);
// Display ins1,ins2,zo_off1
// and zo_off2
System.out.println("Instant ins1 and ins2: ");
System.out.println("ins1: " + ins1);
System.out.println("ins2: " + ins2);
System.out.println();
System.out.println("ZoneOffset zo_off1 and zo_off2: ");
System.out.println("Seconds to add: " + zo_off1);
System.out.println("Hours to add: " + zo_off2);
System.out.println();
// Here, this method merges this Instant(ins1)
// with the given ZoneOffset(zo_off1) i.e. here
// we are adding zo_off1 (10 seconds) with
// the seconds of this Instant (ins1)
OffsetDateTime off_da_time = ins1.atOffset(zo_off1);
// Display off_da_time
System.out.println("ins1.atOffset(zo_off1): " + off_da_time);
// Here, this method merges this Instant(ins2)
// with the given ZoneOffset(zo_off2) i.e. here
// we are adding zo_off2 (2 hours) with
// the hours of this Instant (ins2)
off_da_time = ins2.atOffset(zo_off2);
// Display off_da_time
System.out.println("ins2.atOffset(zo_off2): " + off_da_time);
}
}
Output
Instant ins1 and ins2:
ins1: 2006-04-03T05:10:15Z
ins2: 2007-06-05T10:20:30Z
ZoneOffset zo_off1 and zo_off2:
Seconds to add: +00:00:10
Hours to add: +02:00
ins1.atOffset(zo_off1): 2006-04-03T05:10:25+00:00:10
ins2.atOffset(zo_off2): 2007-06-05T12:20:30+02:00