Wednesday, 21 February 2018

How to set time zone of date and time using withZone methods of ZonedDateTime Class


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

ZoneDateTimeDemo1.java

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

public class ZoneDateTimeDemo1
{

    public static void main(String[] args)
    {

        ZonedDateTime zonedDateTime1 = ZonedDateTime.now();
        System.out.println(zonedDateTime1);

        ZoneId zoneId = ZoneId.of("Z");
        System.out.println(zoneId);

        /*
         * Parameters:
         *
         * zone - the time-zone to change to, not null
         *
         * Returns:
         *
         * a ZonedDateTime based on this date-time with the
         * requested zone, not null
         *
         * If the zone ID equals 'Z', the result is ZoneOffset.UTC.
         */

        ZonedDateTime zonedDateTime2 = zonedDateTime1
                .withZoneSameInstant(zoneId);

        System.out.println(zonedDateTime2);

    }

}

Output

2018-02-07T09:41:43.370+05:30[Asia/Calcutta]
Z
2018-02-07T04:11:43.370Z

ZoneDateTimeDemo2.java

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

public class ZoneDateTimeDemo2
{

    public static void main(String[] args)
    {

        ZonedDateTime zonedDateTime1 = ZonedDateTime.now();
        System.out.println(zonedDateTime1);
       
        ZoneId zoneId = ZoneId.of("Z");
        System.out.println(zoneId);

        /*
         * Parameters:
         *
         * zone - the time-zone to change to, not null
         *
         * Returns:
         *
         * a ZonedDateTime based on this date-time with the
         * requested zone, not null
         *
         * If the zone ID equals 'Z', the result is ZoneOffset.UTC.
         */

        ZonedDateTime zonedDateTime2 = zonedDateTime1
                .withZoneSameLocal(zoneId);
       
        System.out.println(zonedDateTime2);

    }

}

Output

2018-02-07T09:42:07.865+05:30[Asia/Calcutta]
Z
2018-02-07T09:42:07.865Z

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/914905cc2357de2bddb749208190c8f0bf0f9978/BasicJava/ZoneDateTimeDemo_withzone/?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