Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a TimeZone when creating a DateTime object in Dart/Flutter?

Tags:

date

flutter

dart

Dart?flutter does not appear to allow a timezone (eg: "Australia/Sydney" or "America/Detroit") to be specified when creating a DateTime object. Either the local timezone will be used, or UT may be specified.

Is anyone aware of a workaround?

There's the Dart package TimeZone, but it appears to be unusable within a flutter app.

See https://pub.dartlang.org/packages/timezone for the package I'm referring to.

EDIT: The timezone package does work in Flutter, with some setup. See Richard Heap's answer below.

like image 503
Yarm Avatar asked Jun 10 '18 02:06

Yarm


People also ask

How do you convert DateTime to different time zones in Flutter?

You can wrap the DateTime in a custom class and add timezone information to the wrapper. You also need a table of offsets for each timezone and then add/substract the offset from the UTC date.

How do you get UTC time in darts?

Working with UTC and local time Use the methods toLocal and toUtc to get the equivalent date/time value specified in the other time zone. Use timeZoneName to get an abbreviated name of the time zone for the DateTime object. To find the difference between UTC and the time zone of a DateTime object call timeZoneOffset.


2 Answers

You have to do a bit of magic to get package:timezone to work in flutter.

Extract whichever data file you need (there are 3: default, all and 2010-2020) and move it to your flutter assets folder. (I use 2018c_2010-2020.tzf, which is available in a branch.)

Add it as an asset in pubspec.yaml:

  assets:
    - assets/2018c_2010-2020.tzf

Then load that file on startup (e.g. from the initState of a top level StatefulWidget) and use it to initialise the database.

ByteData tzf = await rootBundle.load('assets/2018c_2010-2020.tzf');
initializeDatabase(tzf.buffer.asUint8List());
...
Location newYork = getLocation('US/Eastern');

I haven't tried, but you may even be able to load it from main if you mark it async.

I also notice that I must have cloned the latest branch, as I see this in my pubspec

  timezone:
    path: ../../dart/source/timezone

... but looks like you just need to grab 0.5.0-dev-2 from pub

dependencies:
  timezone: "^0.5.0-dev-2"
like image 79
Richard Heap Avatar answered Oct 13 '22 06:10

Richard Heap


This solution worked for me

simple add these lines in initState


import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
 @override
  void initState() {
   super.initState();
   tz.initializeTimeZones();
   final String locationName = await FlutterNativeTimezone.getLocalTimezone();
   tz.setLocalLocation(tz.getLocation(locationName));
}
like image 26
Arslan Kaleem Avatar answered Oct 13 '22 06:10

Arslan Kaleem