Open dakamojo opened 4 years ago
@dakamojo Doco says you location starts by default as UTC. You need to use setLocalLocation()
to set the local location. Because .toLocal()
relies on what the local timezone is set to, which is UTC by default, which is why you get a UTC time returned from .toLocal()
.
But how do you get the device local timezone, if you don't know it in/have set it advance? There is DateTime.timezoneName
but this is provided by the os and may be abbreviated, so not very helpful, because the setLocalLocation(value)
value must match the tz data file string exactly.
So the original issue question still remains ... how to get in local time zone?
Good questions. I'm not sure if the timezone (or standard Dart APIs) can answer what the device local time zone is.
Ha, I found its even hard for moment.js to answer "what time zone am I in?" "Guessing user zone"
This package somehow knows the answer: https://pub.dev/packages/flutter_native_timezone There is an issue to have this in Dart SDK, without progress: https://github.com/dart-lang/sdk/issues/21758 You may want to upvote it.
@dakamojo you can do it taking into consideration the offset:
final remoteTZDateTime = // ...
final offset = tz.local.name == 'UTC' ? DateTime.now().timeZoneOffset : Duration.zero;
final localTZDateTime = remoteTZDateTime.toLocal().add(offset);
debugPrint('My local time is: $localTZDateTime');
I read the timezone offset only when there's no location set, because in that case the toLocal() returns you the time already localised to your location.
I have a TZDateTime which I happen to know is in EST. My local time zone is CST. If I call toLocal() I get my date in UTC. How can I convert it to the local time zone so that I can properly display it?