简体   繁体   English

在 Kotlin 中将字符串(在数据类中)解码为日期

[英]Decode String (in Data Class) as Date in Kotlin

How would i decode a string, contained in a data class, as a date.我如何将数据类中包含的字符串解码为日期。 I have several strings, which are actually dates ("2022-11-24T23:37:34.668Z") .我有几个字符串,它们实际上是日期("2022-11-24T23:37:34.668Z") These are stored within documents in firebase (obviously there are not only date strings in the documents, but also other types).这些存储在 firebase 的文档中(显然文档中不仅有日期字符串,还有其他类型)。 I want to deserialize so that the strings, which represent dates, are autmatically parsed as such.我想反序列化,以便代表日期的字符串被自动解析。

Currently i decode like so:目前我这样解码:

private inline fun <reified T> parse(snapshot: DocumentSnapshot?): T? {
     return snapshot?.toObject<T>(T::class.java)
}

I do not see a way how to specify a date decoder.我看不到如何指定日期解码器的方法。 Therefore, how do i achieve this.因此,我该如何实现。

There is indeed no way to specify a custom decoder for a specific field/property.确实没有办法为特定字段/属性指定自定义解码器。

The best options I can quickly think of are:我能很快想到的最佳选择是:

  • Add custom functions to the data class to parse the string to a date, and to set a new value as a date and marking them as excluded from the database.将自定义函数添加到数据类以将字符串解析为日期,并将新值设置为日期并将它们标记为从数据库中排除
  • Define a custom class for the string field (eg StringDate ), which handles the same parsing and serializing and then use that in your data class.为字符串字段定义一个自定义类(例如StringDate ),它处理相同的解析和序列化,然后在您的数据类中使用它。

I don't know of existing public implementations of either of these.我不知道其中任何一个的现有公共实现。

Of course the easiest option would be to store the date/time value in a Timestamp field that the Firestore SDK then automatically convert to the native date/time type on each supported platform.当然,最简单的选择是将日期/时间值存储在Timestamp字段中,然后 Firestore SDK 会在每个支持的平台上自动将其转换为本机日期/时间类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM