Wednesday 11 April 2018

How to use atOffset, atZone methods of Instant class | Java 8 Date and Time


Click here to watch on Youtube: 
https://www.youtube.com/watch?v=uZZYAwExVXs&list=UUhwKlOVR041tngjerWxVccw

InstantDemo1.java

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class InstantDemo1
{
    public static void main(String[] args)
    {
        Instant instant = Instant.parse("2017-12-03T10:15:30.00Z");
        System.out.println("instant = " + instant);
        /*
         * Combines this instant with an offset to create an
         * OffsetDateTime.
         *
         * Parameters:
         *
         * offset - the offset to combine with, not null
         *
         * Returns:
         *
         * the offset date-time formed from this instant and the
         * specified offset, not null
         */

        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.UTC);
        System.out.println("offsetDateTime = " + offsetDateTime);
    }

}

Output

instant = 2017-12-03T10:15:30Z
offsetDateTime = 2017-12-03T10:15:30Z

InstantDemo2.java

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class InstantDemo2
{
    public static void main(String[] args)
    {
        Instant instant = Instant.parse("2017-12-03T10:15:30.00Z");
        System.out.println("instant = " + instant);
        /*
         * Combines this instant with a time-zone to create a
         * ZonedDateTime.
         *
         * Parameters:
         *
         * zone - the zone to combine with, not null
         *
         * Returns:
         *
         * the zoned date-time formed from this instant and the
         * specified zone, not null
         */

        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
        System.out.println("zonedDateTime = " + zonedDateTime);
    }

}

Output

instant = 2017-12-03T10:15:30Z
zonedDateTime = 2017-12-03T15:45:30+05:30[Asia/Calcutta]

Click the below link to download the code:
https://sites.google.com/site/ramj2eev2/java_basics/InstantDemo_atOffset_zone.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava_2018/InstantDemo_atOffset_zone

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/dce3f55388a87b7da919bb2501377068a8838f7f/BasicJava_2018/InstantDemo_atOffset_zone/?at=master

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • No comments:

    Post a Comment