DEV Community

loading...

using Timezone package in flutter

shaileshs profile image shaileshs ・1 min read

Timezone package makes life a bit easier to deal with those pain in the neck issues related to timezone. However, I had a bunch of issues using that package, so documenting them here for someone else to save some time.

git clone https://github.com/srawlins/timezone.git
cd timezone
flutter pub get
flutter pub run tool/get -s 2020a
cd lib/data
  • Add it to your codebase.
cp lib/data/2020a* <project_dir>/assets/timezone/
cd <project_dir>
git add->commit->push

Also, add it to your pubspec file under assets with the path you used above.

  • Use it in your code.
  Future<void> initTimezones() async {
    // get device timezone
    String dtz = await FlutterNativeTimezone.getLocalTimezone();

    // Load timezone data
    var byteData = await rootBundle.load('assets/timezone/2020a.tzf');
    tz.initializeDatabase(byteData.buffer.asUint8List());
    tz.initializeTimeZones();
    // set the local location.
    tz.setLocalLocation(tz.getLocation(dtz));

    // Iterate and use through the list of timezones.
    _locations = tz.timeZoneDatabase.locations;
    _locations.values.forEach((element) {
        print(element.name);
        print(element.currentTimeZone.abbr);
        print(element.currentTimeZone.offset);
        print(element.currentTimeZone.isDst);
        print(element.zones.length);
      });
  }
  • For timezone conversion, readme on the package provides great examples, so I will skip repetition.

Hope this helps someone.

Discussion

pic
Editor guide