Instant atOffset() method in Java with Examples
The atOffset(ZoneOffset offset) method of Instant class is used to combine this instant with an offset to create an OffsetDateTime object. This method takes ZoneOffset as a parameter to return an OffsetDateTime object and this OffsetDataTime object is formed from this instant at the specified offset from UTC/Greenwich. If the instant is too large to fit into an offset date-time then the method will throw an exception. This method is same as OffsetDateTime.ofInstant(this, offset).
Syntax:
public OffsetDateTime atOffset(ZoneOffset offset)
Parameters:
This method accepts one parameter offset which is the ZoneOffset to combine with this instant object. It should not be null
Return Value: This method returns the offset date-time formed from this instant and the specified ZoneOffset.
Exception: This method throws DateTimeException if the instant is too large to fit into an offset date-time.
Below programs illustrate the Instant.atOffset() method:
Program 1:
import java.time.*;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-10-20T16:55:30.00Z" );
System.out.println( "Instant: "
+ instant);
ZoneOffset offset = ZoneOffset.ofTotalSeconds( 7200 );
OffsetDateTime offsetDate = instant.atOffset(offset);
System.out.println( "Offset Date and Time: "
+ offsetDate);
}
}
|
Output:
Instant: 2018-10-20T16:55:30Z
Offset Date and Time: 2018-10-20T18:55:30+02:00
Program 2:
import java.time.*;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.parse( "2018-10-20T16:55:30.00Z" );
System.out.println( "Instant: "
+ instant);
ZoneOffset offset
= ZoneOffset.ofHoursMinutes( 3 , 45 );
OffsetDateTime offsetDate
= instant.atOffset(offset);
System.out.println( "Offset Date and Time: "
+ offsetDate);
}
}
|
Output:
Instant: 2018-10-20T16:55:30Z
Offset Date and Time: 2018-10-20T20:40:30+03:45
Program 3:
import java.time.*;
public class GFG {
public static void main(String[] args)
{
Instant instant
= Instant.now();
System.out.println( "Instant: "
+ instant);
ZoneOffset offset
= ZoneOffset
.ofHoursMinutesSeconds( 9 , 45 , 30 );
OffsetDateTime offsetDate
= instant.atOffset(offset);
System.out.println( "Offset Date and Time: "
+ offsetDate);
}
}
|
Output:
Instant: 2018-11-22T08:22:19.846Z
Offset Date and Time: 2018-11-22T18:07:49.846+09:45:30
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#atOffset(java.time.ZoneOffset)
Last Updated :
22 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...