【问题标题】:How to convert DateTime into different timezones?如何将 DateTime 转换为不同的时区?
【发布时间】:2014-10-08 12:57:31
【问题描述】:

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

【问题讨论】:

  • LOOK 此处(参考 Java 脚本)

标签: dart angular-dart


【解决方案1】:

DateTime 不包含时区信息,因此您不能在特定时区创建DateTime,只有系统时区和 UTC 可用。

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

【讨论】:

  • 在 pub.dartlang.org 上弹出了一个似乎可以做到这一点的新包:pub.dartlang.org/packages/timezone
  • DateTime 具有 timeZoneNametimeZoneOffset 属性。
  • 但它只在本地和UTC之间转换
【解决方案2】:

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

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

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

只需一行代码即可轻松完成。

【讨论】:

  • 导入 'package:instant/instant.dart';
  • 嗨,我找不到函数 dateTimeToZone()
  • 您是否导入了即时库?它绝对仍然可用 (pub.dev/documentation/instant/latest/instant/…)
  • 请注意,即时包不支持夏令时,假设全年 UTC 为 -5,它将返回不正确的值。这是一个非首发。更好的方法是使用类似于@Boris 实现的“时区”包。
【解决方案3】:

这是我的 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;
  }
}

【讨论】:

    【解决方案4】:

    您可以使用外部包,例如:timezone
    在此处查看文档:https://pub.dev/packages/timezone

    这是获取洛杉矶时间 (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);
    }
    

    【讨论】:

      【解决方案5】:
      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;
      }
      

      【讨论】:

      • 欢迎来到 SO,如果您添加一些解释来支持您的答案,将会有所帮助。
      • 这个包存在吗?
      • 最好能包含一个工作示例并解释这是什么
      【解决方案6】:

      使用简单的 EPOC 时间而不是其他东西

      var now = DateTime.now().millisecondsSinceEpoch;

      【讨论】:

      • 这如何回答这个问题?拥有 epoch 不足以转换到不同的时区。
      【解决方案7】:

      您可以使用 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");
      }
      

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

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

      【讨论】:

      猜你喜欢
      • 2018-12-18
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      相关资源
      最近更新 更多