srawlins / timezone

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

Is there a way to override the system time zone in flutter for unit testing? #156

Open Quesajo17 opened 1 year ago

Quesajo17 commented 1 year ago

I have a Date class that only stores a DateTime, but is supposed to convert it to the current date (regardless of time zone) at 00:00:0000 in UTC.

I would like unit tests to make sure it works on both ends of the UTC timezone, to make sure it is working properly. Is there a way to update the system timezone in flutter to do this? It seems like the setLocalLocation(X) method doesn't work in dart.

HenriqueNas commented 1 month ago

With the Intl package you can set the locale:

    Intl.defaultLocale = 'pt_BR';
    Intl.systemLocale = 'pt_BR';

But, to inject the current date-time of your application you must use a provider, by creating your self, or using the clock package, provided by Dart:

void main() {
  final fixedDateTime = DateTime(1997, 12, 16);
  withClock(
    Clock.fixed(fixedDateTime),
    () async {
      print(clock.now()); // 1997-12-16 00:00:00.000
    },
  );
}

but you need to replace all DateTime.now() by clock.now()

provokateurin commented 3 weeks ago

You can just override the location using tz.setLocalLocation(tz.getLocation('Europe/Berlin')); which is exactly what I'm doing in my tests. I don't know why it wouldn't work for you.