如何在特定时区中创建DateTime实例?

时间:2018-09-10 19:25:55

标签: dart

我正在调用旧服务,该服务以时区为EST的形式以字符串格式返回所有时间。如何创建DateTime实例并指定时区为EST?当我向用户显示时间时,我将转换为他们的设备时区。

2 个答案:

答案 0 :(得分:0)

包含的DateTime类仅支持本地时区或UTC,但不支持特定时区。

https://pub.dartlang.org/packages/timezone可以提供这一点,但似乎需要针对Dart 2.0.0进行更新

https://pub.dartlang.org/packages/time_machine是较新的版本。

答案 1 :(得分:0)

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

在时区中获取DateTime的基本用法非常简单。

注意:我在下面假设您的旧服务在24小时内交付格式为HH:MM的字符串,并且不交付日期。如果以下任何一个不正确,我就知道了,我将更改代码示例。

List<int> _hourmin (String parse) {
  List<int> timeinint = [];
  if (parse.length == 5) {
    //if parse is something like 10:00
    timeinint.add(int.parse(parse.substring(0,2))); //Add hours (10)
    timeinint.add(int.parse(parse.substring(3,5))); //Add minutes (0)
  } //hours >= 10
  if (parse.length == 4) {
    //if parse is something like 4:06
    timeinint.add(int.parse(parse.substring(0,1))); //Add hours (4)
    timeinint.add(int.parse(parse.substring(2,4))); //Add minutes (6)
  } //hours < 10
  return timeinint;
}

DateTime utcDateTimeFromZone(
    {@required String zone,
    int year = 0,
    int month = 0,
    int day = 0,
    int hour = 0,
    int minute = 0,
    int second = 0,
    int millisecond = 0,
    int microsecond = 0}) {

  hour = (hour - timeZoneOffsets[zone].truncate()) % 24; //Convert to UTC from timezone
  if (hour<0) {
    hour = 24 + hour;
  }
  minute = (minute - ((timeZoneOffsets[zone]%1)*60).round()) % 60;
  if (minute<0) {
    minute = 60 + minute;
  }
//Convert to UTC from timezone
  DateTime inUTC = DateTime.utc(year, month, day, hour, minute, second, millisecond, microsecond); //Initialize in UTC time
  return inUTC;
}

  //We get an array containing the hours minutes
  List<int> time = _hourmin("4:25"); //put your API call as the param here
  //This is what you need
  DateTime finished = utcDateTimeFromZone(zone: "EST", hour: time[0], minute: time[1]);

  print(formatTime(time: finished.toLocal())); //1:25 for me, because I'm PST, but this works with any local timezone

希望可以清除它!