如何将DateTime转换为不同的时区?

时间:2014-10-08 12:57:32

标签: dart angular-dart

如何将DateTime转换为不同的时区? DateTime类有两个方法.toLocal()和.toUtc()。 但是,如果我想在另一个时区显示时间。我该怎么办?

5 个答案:

答案 0 :(得分:2)

DateTime不包含时区信息,因此您无法在特定时区内仅在系统时区和UTC可用时创建DateTime

您可以将DateTime包装在自定义类中,并将时区信息添加到包装器中。您还需要每个时区的偏移表,然后添加/减去UTC日期的偏移量。

答案 1 :(得分:2)

这是我针对 EST 时区的解决方案,但您可以将其更改为任何其他时区

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;
  }
}

答案 2 :(得分:0)

您可以使用TimeZoneInfo.ConvertTime()来更改时区。试试这个

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");
}

这将从夏威夷标准时间转换为本地时间。

这只是一个例子。使用它根据您的需要进行转换。

答案 3 :(得分: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;
}

答案 4 :(得分:-1)

我为此编写了一个程序包。它称为Instant,它可以转换全球任何给定时区中的DateTime。详细了解https://aditya-kishore.gitbook.io/instant/

将DateTime转换为时区的基本用法非常简单:

//Assumes Instant is in your pubspec
import 'pacakges:instant/instant.dart';

//Super Simple!
DateTime myDT = DateTime.now(); //Current DateTime
DateTime EastCoast = dateTimeToZone(zone: "EST", datetime: myDT); //DateTime in EST zone
return EastCoast;

这适用于一行代码,并且麻烦最少。