srawlins / timezone

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

convertDateTimeToCurrentTimeZone #170

Closed Tigran-Kosemyan closed 1 year ago

Tigran-Kosemyan commented 1 year ago

origin date always in for example Europe/Paris time zone device time zone is other,

tz.initializeTimeZones(); tz.setLocalLocation(tz.getLocation('Europe/Paris')); DateTime originalDateTime = DateTime.parse('2023-04-25 19:00:00'); final detroit = tz.getLocation('my current time zone'); var detroitTime = tz.TZDateTime.from(originalDateTime, detroit);

not converting in other time zone always return current date

Tigran-Kosemyan commented 1 year ago

Solution 2023-04-25 19:00:00 adding enpiont to incoming date 000000+0200

ikbendewilliam commented 11 months ago

What do you mean adding +0200 fixed it? This is not correct in the winter is it?

Tigran-Kosemyan commented 11 months ago

its closed you can ignore this

ikbendewilliam commented 11 months ago

Well I think your solution might break in a few months and someone else might encounter the same issue.

How we solved it is in the following way:

  static TZDateTime parseFromBelgium(String formattedString) {
    final belgianAsUTCTime = DateTime.parse(formattedString);
    return TZDateTime(
      _belgianTimeZone,
      belgianAsUTCTime.year,
      belgianAsUTCTime.month,
      belgianAsUTCTime.day,
      belgianAsUTCTime.hour,
      belgianAsUTCTime.minute,
      belgianAsUTCTime.second,
      belgianAsUTCTime.millisecond,
      belgianAsUTCTime.microsecond,
    );
  }

We receive a time like this: 2023-04-25 19:00:00 but it's localized as +2 (for now, in the winter it will be +1). So we process it like it's UTC (by adding Z to the end of it) to make sure it's not changed. We then add that to the TZDateTime constructor and then it's processed correctly and we convert it to the TZ of the user with

  static TZDateTime toLocal(DateTime dateTime) => TZDateTime.from(dateTime, local);

And this is how we use it:

  TZDateTime toDateTime(String date, String time) {
    final belgianTime = TimeZoneUtil.parseFromBelgium('${date}T$time.000Z');
    return TimeZoneUtil.toLocal(belgianTime);
  }

Hope it helps someone 🙂

Tigran-Kosemyan commented 11 months ago

thank you for help