如何将flutter中的日期解析为与Java ZonedDateTime兼容的json字符串

Posted

技术标签:

【中文标题】如何将flutter中的日期解析为与Java ZonedDateTime兼容的json字符串【英文标题】:How to parse a date in flutter to a json string compatible with Java ZonedDateTime 【发布时间】: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,如果它也对你有用,请记得接受答案。 【参考方案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

【讨论】:

以上是关于如何将flutter中的日期解析为与Java ZonedDateTime兼容的json字符串的主要内容,如果未能解决你的问题,请参考以下文章

kotlinx.serialization :如何解析为与 JSON 键的确切名称不同的变量名称

在java中将RSS pubDate解析为日期对象

java - 如何在Java中使用带有@JsonFormat的'dd-MMM-yyyy'来解析日期?

在 Flutter 中解析 JSON 日期

如何在 BigQuery SQL 中为与按日期排序的主 ID 关联的子 ID 编号?

将java字符串转换为与replaceAll中的正则表达式兼容的字符串[重复]