Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Timezone (as ZoneId)

I am relative new to Flutter. While I was experimenting, I came across with an issue. My REST Api takes a timezone parameter (Zone ID format such as Europe/London).

I saw both https://pub.dartlang.org/packages/flutter_native_timezone and https://pub.dartlang.org/packages/timezone, but neither of those serve my needs.

My goal is, when the user connect to the internet (without giving any location access to the app, if it is possible), get the timezone in ZoneId format and feed my back end in order to make the necessary date and time adjustments. Something similar to this

>>> var timezone = jstz.determine();
>>> timezone.name(); 
"Europe/London"

Presented in https://bitbucket.org/pellepim/jstimezonedetect

Any insights will be really helpful.

Thanks in advance

like image 821
Pan Avatar asked Jul 16 '18 12:07

Pan


People also ask

How do you get timezone with DateTime in flutter?

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.


3 Answers

I've been also looking for this and here's what I found: https://pub.dev/packages/flutter_native_timezone

It a bit hacky under the hood, but it seems to work properly on both iOS and Android. Hope this will help someone in need.

Usage:

final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
print(currentTimeZone); // Europe/Moscow
like image 172
Alexander Krol Avatar answered Nov 15 '22 09:11

Alexander Krol


Came up with a simple solution:

//server time(UTC)
String date_to_parse = "2019-06-23 12:59:43.444896+00:00";
DateTime server_datetime = DateTime.parse(date_to_parse);

//get current system local time
DateTime local_datetime = DateTime.now();

//get time diff
var timezoneOffset = local_datetime.timeZoneOffset;
var time_diff = new Duration(hours: timezoneOffset.inHours, minutes: timezoneOffset.inMinutes % 60);

//adjust the time diff
var new_local_time = server_datetime.add(time_diff);
like image 23
dsalkamoses Avatar answered Nov 15 '22 09:11

dsalkamoses


You can simply add .toLocal() to your DateTime object.

myDate = otherDate.toLocal();

myDate = DateTime.parse(json['server_date']).toLocal();
like image 33
Karim Avatar answered Nov 15 '22 10:11

Karim