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

4.2k Views Asked by At

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?

2

There are 2 best solutions below

0
Abdullah Obeid On BEST ANSWER

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);
}
0
Matthias Ngeo On

Disclaimer: I'm one of the authors of Sugar.

You can use the "sugar" package:

dependencies:
  sugar: ^3.0.0

To use the package:

import 'package:sugar/sugar.dart';

void currentTime() {
  final now = ZonedDateTime.now(Timezone('Europe/Istanbul'));
}

See ZonedDateTime for more information.