将日期字符串转换为Kotlin中的日期对象?如何计算从今天到Kotlin的具体日期之间的天数



第1部分:我有以下格式的字符串形式的日期:;2020-10-15T22:54:54Z";我必须把它转换成日期对象。尝试了以下操作:

val dateString = "2020-10-15T22:54:54Z"
val dateFormatter = DateTimeFormatter.ofPattern("%Y-%m-%dT%H:%M:%SZ")
val updatedAtDate = LocalDate.parse(dateString, dateFormatter)
val today = LocalDateTime.now()
println("Updated At: $updatedAtDate")

给出以下错误:;未知图案字母:T";

第2部分:一旦我有了上面的日期对象,我就必须计算今天(当前日期(和上面日期之间的差额。如何在科特林做到这一点?

tl;dr您不需要创建自定义格式化程序

…对于这里的val dateString = "2020-10-15T22:54:54Z",它是按照ISO标准格式化的。因此,您可以简单地这样做(如果您想要LocalDate,只需年、月和日(:

val thatDate: LocalDate = OffsetDateTime.parse(dateString).toLocalDate()

充分处理您帖子的所有方面:

您可以使用java.time.Period.between(LocalDate, LocalDate)来计算两个LocalDate之间的差异。您只需要确保较早的日期是第一个参数,否则会得到否定的结果。下面是一个完整的例子:

import java.time.OffsetDateTime
import java.time.LocalDate
import java.time.Period
fun main(args: Array<String>) {
val dateString = "2020-10-15T22:54:54Z"
// create an OffsetDateTime directly
val thatDate = OffsetDateTime.parse(dateString)
// and extract the date
.toLocalDate()
// get the current day (date only!)
val today = LocalDate.now()
// calculate the difference in days and make sure to get a positive result
val difference = if (today.isBefore(thatDate))
Period.between(today, thatDate).days
else
Period.between(thatDate, today).days
// print something containing both dates and the difference
println("[$today] Updated At: $thatDate, difference: $difference days")
}

2021年12月10日的产量:

[2021-12-10] Updated At: 2020-10-15, difference: 25 days

最新更新