11 C
New York
Thursday, November 23, 2023

Flutter: Convert UTC Time to Local Time and Vice Versa

This short and straightforward article is about converting UTC time to local time and vice versa in Flutter. Without any further ado, letÂ’s get to the point.

See Your Current Timezone

You can get your current timezone by making use of the timeZoneName property of the DateTime class:Advertisements

// main.dart
void main() {
  print(DateTime.now().timeZoneName);
}

You will get something like this:

-05

UTC Time to Local Time

The DateTime class has a method called toLocal() that returns a DateTime value to the local time zone.

Example:

// main.dart
void main() {
  // Create a UTC DateTime object
  // 2022-02-03 10:30:45
  final _utcTime = DateTime.utc(2022, 2, 3, 10, 30, 45);

  // Get local time based on UTC time
  final _localTime = _utcTime.toLocal();
  print(_localTime);
}

Output:

2022-02-03 05:30:45.000
// EST or UTC - 05:00

Local Time to UTC Time

To convert local time to UTC time, we the toUtc() method.

Example:

// main.dart
void main() {
  // UTC - 5:00 (EST)
  final _localTime = DateTime(2022, 02, 03, 10, 22, 59);

  // Convert to UTC time
  final _utcTime = _localTime.toUtc();
  print(_utcTime);
}
Advertisements

Output:

2022-02-03 15:22:59.000Z

You can find more information about the DateTime class in the official docs.

Afterword

YouÂ’ve learned how to turn UTC time into local time and vice versa in Flutter. Continue exploring more about this awesome SDK by taking a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles