Tuesday, 27 February 2018

How to use ofInstant methods of ZonedDateTime Class | Java 8 Date and Time


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

ZoneDateTimeDemo1.java

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

public class ZoneDateTimeDemo1
{

    public static void main(String[] args)
    {
        Instant instant = Instant.now();
        System.out.println(instant);

        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId);

        /*
         *
         * Obtains an instance of ZonedDateTime from an Instant.
         *
         * Parameters:
         *
         * instant - the instant to create the date-time from, not
         * null
         *
         * zone - the time-zone, not null
         *
         * Returns:
         *
         * the zoned date-time, not null
         */

        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
        System.out.println(zonedDateTime);

    }

}

Output

2018-02-11T04:05:47.632Z
Asia/Calcutta
2018-02-11T09:35:47.632+05:30[Asia/Calcutta]

ZoneDateTimeDemo2.java

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class ZoneDateTimeDemo2
{

    public static void main(String[] args)
    {

        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);

        ZoneOffset zoneOffset = ZoneOffset.UTC;
        System.out.println(zoneOffset);

        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId);

        /*
         * Parameters:
         *
         * localDateTime - the local date-time, not null
         *
         * offset - the zone offset, not null
         *
         * zone - the time-zone, not null
         *
         * Returns:
         *
         * the zoned date-time, not null
         *
         */


        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(localDateTime,
                zoneOffset, zoneId);
        System.out.println(zonedDateTime);
    }

}

Output

2018-02-11T09:35:59.355
Z
Asia/Calcutta
2018-02-11T15:05:59.355+05:30[Asia/Calcutta]

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ZoneDateTimeDemo_ofInstant_methods.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ZoneDateTimeDemo_ofInstant_methods

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/f479c67d9d2a797db17daef3132e32f3fda78b25/BasicJava/ZoneDateTimeDemo_ofInstant_methods/?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
  • No comments:

    Post a Comment