How to convert DateTime into different timezones? How to convert DateTime into different timezones? dart dart

How to convert DateTime into different timezones?


DateTime doesn't contain timezone information therefore you can't create a DateTime in a specific timezone only the timezone of your system and UTC are available.

You can wrap the DateTime in a custom class and add timezone information to the wrapper. You also need a table of offsets for each timezone and then add/substract the offset from the UTC date.


I wrote a package for this. It's called Instant, and it can convert a DateTime in any given timezone worldwide. Take a detailed look at https://aditya-kishore.gitbook.io/instant/

The basic usage for converting a DateTime to a timezone is very simple:

//Assumes Instant is in your pubspecimport 'package:instant/instant.dart';//Super Simple!DateTime myDT = DateTime.now(); //Current DateTimeDateTime EastCoast = dateTimeToZone(zone: "EST", datetime: myDT); //DateTime in EST zonereturn EastCoast;

This works with one line of code and minimal hassle.


Here is my solution for EST time zone but you can change it to any other

import 'package:timezone/data/latest.dart' as tz;import 'package:timezone/timezone.dart' as tz;extension DateTimeExtension on DateTime {  static int _estToUtcDifference;  int _getESTtoUTCDifference() {    if (_estToUtcDifference == null) {      tz.initializeTimeZones();      final locationNY = tz.getLocation('America/New_York');      tz.TZDateTime nowNY = tz.TZDateTime.now(locationNY);      _estToUtcDifference = nowNY.timeZoneOffset.inHours;    }    return _estToUtcDifference;  }  DateTime toESTzone() {    DateTime result = this.toUtc(); // local time to UTC    result = result.add(Duration(hours: _getESTtoUTCDifference())); // convert UTC to EST    return result;  }  DateTime fromESTzone() {    DateTime result = this.subtract(Duration(hours: _getESTtoUTCDifference())); // convert EST to UTC    String dateTimeAsIso8601String = result.toIso8601String();    dateTimeAsIso8601String += dateTimeAsIso8601String.characters.last.equalsIgnoreCase('Z') ? '' : 'Z';    result = DateTime.parse(dateTimeAsIso8601String); // make isUtc to be true    result = result.toLocal(); // convert UTC to local time    return result;  }}