我有一个格式为“2021-07-14T13:00:00.000+0300”(或类似格式)的日期值。我想将其转换为Date
. 在这种情况下,我必须遍历不同格式的循环并检查它们是否失败。
import java.text.*
import java.util.*
val formats = listOf(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
"dd.MM.yyyy, EEEE, HH:mm" // And many others.
)
val date = "2021-07-14T13:00:00.000+0300"
val locale = Locale.getDefault()
for (format in formats) {
try {
return SimpleDateFormat(format, locale).parse(date)
} catch (e: ParseException) {
}
}
// If nothing found, return current date.
return Date()
如何将此for循环转换为类似的东西map
?这样我们就可以无一例外地得到第一个值?
val result = formats.map { ... }
另一个选项,虽然仍在使用firstNotNullOfOrNull()
,但parse()
与一个ParsePosition
对象一起使用,当与setLenient(false)
*结合使用时,您可以安全地忽略其属性。
该parse(String, ParsePosition)
版本的优势parse(String)
在于它null
在无法解析日期时返回,而不是抛出错误,因此可以避免每次迭代的 try-catch 开销。
除此之外,由于如果所有格式都失败,您将默认为当前日期,因此您可以在最后使用 Elvis 操作避免可空日期类型结果。
val result: Date = formats.firstNotNullOfOrNull { format ->
with (SimpleDateFormat(format, locale)) {
setLenient(false) // may not be required, see below
parse(date, ParsePosition(0)) // is null or Date
}
} ?: Date()
顺便说一句,setLenient(false)
可能不需要,因为在 v15 上,SimpleDateFormat.parse()
文档中没有宽大处理……但它的行为确实很宽大。将其设置为true
above 或将其省略,并解析生产日期(注意“53”)。毫不留情,它产生. 抽象基类中提到了宽大处理,但没有提到."2021-07-14T53:00:00.000+0300"
Fri Jul 16 02:00:00 UTC 2021
null
DateFormat.parse(String, ParsePosition)
SimpleDateFormat.parse(String, ParsePosition)
因此,如果您期望非模式匹配日期而不是无效但模式匹配日期,则上述循环可以简化为:
val result: Date = formats.firstNotNullOfOrNull { format ->
SimpleDateFormat(format, locale).parse(date, ParsePosition(0))
} ?: Date()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句