24

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?

Sergey
  • 425
  • 1
  • 4
  • 11

9 Answers9

11

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
11

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;
  }
}
Boris
  • 363
  • 3
  • 12
7

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.

AKushWarrior
  • 504
  • 3
  • 16
  • import 'package:instant/instant.dart'; – nunuh89 Nov 01 '20 at 05:33
  • Hi, am not able to find the function dateTimeToZone() – Priya Sindkar Apr 13 '21 at 07:07
  • Have you imported the instant library? It's definitely still available (https://pub.dev/documentation/instant/latest/instant/instant-library.html) – AKushWarrior May 17 '21 at 15:23
  • Note that the instant package is not daylight saving's time aware and it will return incorrect values assuming -5 from UTC year-round. This is a non-starter. The better approach is to use the "timezone" package similar to @Boris's implementation. – Pat Jul 09 '21 at 16:39
4

You can use an external package, like: timezone.
See docs here: https://pub.dev/packages/timezone

Here's a sample code to get the time in Los Angeles (PST/PDT).

import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;

DateTime _getPSTTime() {
  tz.initializeTimeZones();

  final DateTime now = DateTime.now();
  final pacificTimeZone = tz.getLocation('America/Los_Angeles');

  return tz.TZDateTime.from(now, pacificTimeZone);
}
Marius Pop
  • 334
  • 2
  • 6
0
import 'package:timezone/timezone.dart'

String locationLocal = await FlutterNativeTimezone.getLocalTimezone();

//Esta Função recebe uma data/hora e converte para data/hora local.
TZDateTime convertFireBaseToLocal(TZDateTime tzDateTime, String locationLocal) {
      TZDateTime nowLocal = new TZDateTime.now(getLocation(locationLocal));
      int difference = nowLocal.timeZoneOffset.inHours;
      TZDateTime newTzDateTime;
      newTzDateTime = tzDateTime.add(Duration(hours: difference));
      return newTzDateTime;
}
0

I modified Boris answer to pretend as user is in EST, otherwise time is adjusted to UTC:

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 = toUtc(); // local time to UTC
    result = result.add(Duration(hours: _getESTtoUTCDifference()));
    // convert UTC to EST and remove ZULU as it is not UTC anymore.
    String dateTimeAsIso8601String =
        result.toIso8601String().replaceAll('Z', '');
    result = DateTime.parse(dateTimeAsIso8601String);
    return result;
  }

  DateTime fromESTzone() {
    DateTime result = subtract(
        Duration(hours: _getESTtoUTCDifference())); // convert EST to UTC

    String dateTimeAsIso8601String = result.toIso8601String();
    dateTimeAsIso8601String += dateTimeAsIso8601String.endsWith('Z') ? '' : 'Z';
    result = DateTime.parse(dateTimeAsIso8601String); // make isUtc to be true

    result = result.toLocal(); // convert UTC to local time
    return result;
  }
}
0

Convert To IST for example, if not interested to use any non-verified lib in production.

DateTime.now().toUtc().add(const Duration(hours: 5, minutes: 30));

kamal
  • 996
  • 15
  • 25
-2

use simple EPOC time istead of other stuff

var now = DateTime.now().millisecondsSinceEpoch;

-8

You can use TimeZoneInfo.ConvertTime() to change timezone. Try like this

DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00);
try {
    TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
    TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local));
}
catch (TimeZoneNotFoundException) {
    Console.WriteLine("Timezone not found");
}                           
catch (InvalidTimeZoneException) {
    Console.WriteLine("Invalid Timezone");
}

This will convert from Hawaiian Standard Time to Local.

It is just an example. Use it to convert as per your need.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
jjchr
  • 105
  • 3