Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DateTime into different timezones?

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?

like image 426
Sergey Avatar asked Oct 08 '14 12:10

Sergey


2 Answers

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.

like image 147
Günter Zöchbauer Avatar answered Oct 02 '22 23:10

Günter Zöchbauer


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.

like image 40
AKushWarrior Avatar answered Oct 03 '22 01:10

AKushWarrior