【问题标题】:How to parse a date in flutter to a json string compatible with Java ZonedDateTime如何将flutter中的日期解析为与Java ZonedDateTime兼容的json字符串
【发布时间】:2019-12-15 14:32:00
【问题描述】:

我有一个 Flutter 应用程序需要向我的 Spring Boot 应用程序发送一个发布请求。发送的对象必须具有与 ZonedDateTime java 类兼容的 json 字符串格式的 Date。 模式应该是:yyyy-MM-ddTHH:mm[:ss[.S]]ZZ[{ZoneId}] 日期格式正确的示例:

{
   'date':'2007-12-03T10:15:30+01:00[Europe/Paris]'
}

我尝试在 pub.dev 上使用 time_machine 0.9.9 库,但它没有生成正确的模式。这是一个例子:

import 'package:time_machine/time_machine.dart';

Map<String, dynamic> toJson() => <String, dynamic>{
    'date': '${Instant.now().inLocalZone()}'
}

生成:

{
    "date":"2019-08-07T22:24:54 UTC (+00)"
}

Spring boot 应用抛出异常:

org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Cannot deserialize value of type `java.time.ZonedDateTime` from String "2019-08-07T22:24:54 UTC (+00)": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '2019-08-07T22:24:54 UTC (+00)' could not be parsed at index 19

【问题讨论】:

  • 一个大胆的猜测:如果你使用Instant.now() 而不使用.inLocalZone(),你会得到2019-08-07T22:24:54Z,这对于你的Spring Boot 应用来说应该没问题。
  • @OleV.V.谢谢这对我有用。
  • 谢谢,@hizmarck。在这种情况下,我想将其发布为答案。 J. Gatica,如果它也对你有用,请记得接受答案。

标签: json rest spring-boot flutter zoneddatetime


【解决方案1】:

如果你只使用Instant.now() 而不使用.inLocalZone(),你会得到2019-08-07T22:24:54Z,这对于你的Spring Boot 应用来说应该没问题。

2019-08-07T22:24:54Z 是 ISO 8601 格式,这是 java.time API 中现代 Java 日期和时间类的默认格式。所以 Java ZonedDateTime 可以很好地解析它。错误消息说ZonedDateTime 无法解析您从inLocalZone() 获得的字符串,引用为2019-08-07T22:24:54 UTC (+00)

这最初是在评论中作为猜测发布的,但另一位用户确认它对他/她有用,之后我发布了这个答案。

链接。 Wikipedia article: ISO 8601

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2023-03-09
    • 2012-07-11
    相关资源
    最近更新 更多