srawlins / timezone

Time zone database and time zone aware DateTime object for Dart.
BSD 2-Clause "Simplified" License
102 stars 54 forks source link

toLocal returns a time in UTC, how to get in local time zone? #50

Open dakamojo opened 4 years ago

dakamojo commented 4 years ago

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?

workerbee22 commented 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?

srawlins commented 4 years ago

Good questions. I'm not sure if the timezone (or standard Dart APIs) can answer what the device local time zone is.

srawlins commented 4 years ago

Ha, I found its even hard for moment.js to answer "what time zone am I in?" "Guessing user zone"

alexeyinkin commented 2 years ago

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.

alefwd commented 6 months ago

@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.