【问题标题】:Parse JSON date in Flutter在 Flutter 中解析 JSON 日期
【发布时间】:2019-10-23 15:07:44
【问题描述】:

我应该在 Flutter 应用程序中使用的 API 响应包含 JSON 格式的日期,格式如下:/Date(1559985189000+0300)/

解析时出现以下异常: FormatException (FormatException: 无效的日期格式 /日期(1559985189000+0300)/)

我用这段代码解析:date: DateTime.parse(json["Date"])

日期字符串对我来说似乎是一个 unix 时间戳。

Flutter 中是否有内置方法可以将此日期字符串解析为 DateTime,还是应该实现它?

非常感谢!

【问题讨论】:

    标签: json datetime parsing flutter


    【解决方案1】:

    你必须实现它;而且您将不得不进行一些实验,因为您还没有说出您的服务器实际提供的内容。另外值得注意的是,Dart 的日期仅支持两个时区:UTC 或本地时间。 (timezone 包提供了整个 Olsen 数据库,用于处理其他时区。)

    从问题中的数字猜测,当你问它时,假设日期是 UTC,但服务器是 UTC+3(例如,希腊雅典)。

    首先解析出相关位:

      var raw = '/Date(1559985189000+0300)/';
    
      var numeric = raw.split('(')[1].split(')')[0];
      var negative = numeric.contains('-');
      var parts = numeric.split(negative ? '-' : '+');
      var millis = int.parse(parts[0]);
    

    这将在手机的 TZ 中为您提供DateTime

      var local = DateTime.fromMillisecondsSinceEpoch(millis);
    

    这将为您提供 UTC 时间:

      var utc = DateTime.fromMillisecondsSinceEpoch(millis, isUtc: true);
    

    这将使您获得雅典和 UTC 之间的偏移量,但可能没用时区包 - Dart 仅支持 UTC 或手机时间,可能在苏黎世)

      final multiplier = negative ? -1 : 1;
      var offset = Duration(
        hours: int.parse(parts[1].substring(0, 2)) * multiplier,
        minutes: int.parse(parts[1].substring(2)) * multiplier,
      );
    

    【讨论】:

    • 非常感谢您的详细解释!
    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多