How to use timeZone abbreviation and TimeZoneOffset while creating DateTime Object in flutter?

125

Quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Also, do not use non-standard IDs like CT, ET. Use the standard IDs like America/New_York, America/Mexico_City.

Solution using java.time, the modern Date-Time API:

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

public class Main {
    public static void main(String[] args) {
        Instant now = Instant.now();

        ZonedDateTime zdtUsEastern = now.atZone(ZoneId.of("America/New_York"));
        System.out.println(zdtUsEastern);

        ZonedDateTime zdtUsCentral = now.atZone(ZoneId.of("America/Mexico_City"));
        System.out.println(zdtUsCentral);

        // If you have to deal with just one time zone, you can use ZonedDateTime
        // directly (i.e. without using Instant)
        ZonedDateTime zdtLondon = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
        System.out.println(zdtLondon);

        // ZonedDateTime in JVM's time zone
        ZonedDateTime zdtJvmDefault = ZonedDateTime.now();
        System.out.println(zdtJvmDefault);
    }
}

Output from a sample run in my timezone, Europe/London:

2021-07-27T12:46:56.478657-04:00[America/New_York]
2021-07-27T11:46:56.478657-05:00[America/Mexico_City]
2021-07-27T22:16:56.543040+05:30[Asia/Kolkata]
2021-07-27T17:46:56.547117+01:00[Europe/London]

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Share:
125
Tharani
Author by

Tharani

Updated on December 31, 2022

Comments

  • Tharani
    Tharani over 1 year

    Using timezone abbreviation (Eg: CT, ET) and timeZoneOffset, I want to create a DateTime Object with a specified timezone. But I am always getting the date in current timezone.

    But DateTime object should be specified timezone. But in flutter, I did not find the option to specify the timezone while creating a DateTime Object.

    • Arvind Kumar Avinash
      Arvind Kumar Avinash over 2 years
      Do not use non-standard IDs like CT, ET. Use the standard IDs like America/New_York, America/Mexico_City.
    • Basil Bourque
      Basil Bourque over 2 years
      CT, ET, CST, IST, and such are not real time zone names. Real time zone names have a Continent/Region format such as America/New_York, Africa/Tunis, and Asia/Tokyo.
  • Randal Schwartz
    Randal Schwartz over 2 years
    How is a Java answer relevent to a Flutter question?