json - 在 Flutter 中解析 JSON 日期

标签 json datetime parsing flutter

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

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

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

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

在 Flutter 中是否有内置的方法将此日期字符串解析为 DateTime,或者我应该实现它吗?

非常感谢!

最佳答案

你必须实现它;并且您将不得不进行一些实验,因为您还没有说出您的服务器实际提供的内容。另外值得注意的是 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 之间的偏移量,但可能没有用:(请注意,即使我们可以推断您的服务器位于雅典(或类似的 TZ),我们也无法在不使用雅典时区的情况下获取日期timezone 包 - 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,
  );

关于json - 在 Flutter 中解析 JSON 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505658/

相关文章:

javascript - 是否有任何简写方法将以标题作为第一个数组的字符串数组转换为数组对象?

javascript - d3 时间格式返回 null

python - BeautifulSoup 3.1 解析器太容易崩溃了

java - 在java中更快地解析json

c# - 带有 POST 的 ASP.NET MVC JSON 正文

javascript - Angular 5 服务读取本地 .json 文件

android webview 使用 json 发布和响应

python - 尝试编写时间增量函数

excel - 倒计时到 VBA 中的特定日期和时间

php - 解析 PHP 中的属性/值列表