Flutter Timezone (as ZoneId)

扶醉桌前 提交于 2020-01-04 01:29:33

问题


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


回答1:


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



回答2:


After doing some digging, I found a (temporary) workaround to my issue.

Using

var now = new DateTime.now();
var timezoneOffset = now.timeZoneOffset;

I got the timezoneOffset in UTC format in flutter. Then send it to my back end as string (i.e. "-04") and drift my ZoneId properly.

Integer tzOffsetHour = Integer.valueOf(covertToTimezone);
ZoneOffset offset = ZoneOffset.ofHoursMinutes(tzOffsetHour, 0);
ZoneId zoneTZ = ZoneId.ofOffset("UTC", offset);
LocalDateTime localDateTimeClient = new Date().toInstant().atZone(zoneTZ).toLocalDateTime();

As a result I take the local time and date as stated in user's device, without using any location services, which was my goal from the beginning.

Until now, I have not faced any issues... we will see...




回答3:


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);



回答4:


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

myDate = otherDate.toLocal();

myDate = DateTime.parse(json['server_date']).toLocal();


来源:https://stackoverflow.com/questions/51361843/flutter-timezone-as-zoneid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!