How to convert DateTime into different timezones? The DateTime class has two methods .toLocal() and .toUtc(). But if I want to display time in another time zone. How can I do it?
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 pubspec
import 'package:instant/instant.dart';
//Super Simple!
DateTime myDT = DateTime.now(); //Current DateTime
DateTime EastCoast = dateTimeToZone(zone: "EST", datetime: myDT); //DateTime in EST zone
return EastCoast;
This works with one line of code and minimal hassle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With