1

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.

Tharani
  • 51
  • 4
  • 1
    Do not use non-standard IDs like CT, ET. Use the [standard IDs](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) like `America/New_York`, `America/Mexico_City`. – Arvind Kumar Avinash Jul 27 '21 at 16:32
  • CT, ET, CST, IST, and such are not [real time zone names](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Real time zone names have a `Continent/Region` format such as `America/New_York`, `Africa/Tunis`, and `Asia/Tokyo`. – Basil Bourque Jul 27 '21 at 16:32

1 Answers1

2

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110