Search code examples
fluttertimezonecountrycity

How to get time zone by country or city in Flutter?


Can I get the timezone by passing the city and country as parameters in Flutter?

I'm using DateTime class to get a timezone like this:

DateTime var;
print('${var.timeZoneName}'); // -> +3

What I need is to get same result above by passing country/city as parameters, something like that:

Country country; // This is how the model is required, Country is a customized class
print('${country.city.timeZoneName}'); // -> +3

The question is how to resolve time zone for a city object in someway?


Solution

  • First you need to add "timezone" package

    dependencies:
     timezone: ^0.8.0
    

    then it is used like this as example:

    import 'package:timezone/timezone.dart' as tz;
    import 'package:timezone/data/latest.dart' as tz;
    
    void main() {
      tz.initializeTimeZones();
    }
    
    
    Future<void> setup() async {
      await tz.initializeTimeZones();
      var istanbulTimeZone = tz.getLocation('Europe/Istanbul');
      var now = tz.TZDateTime.now(istanbulTimeZone);
    }