在Android Kotlin中查找日期之间的天差 [英] Finding days difference between dates in Android Kotlin
本文介绍了在Android Kotlin中查找日期之间的天差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我已经在Google上进行搜索,其中大多数使用Java,其中有一种使用Kotlin,并且经常使用与我使用的时间格式不同的时间格式(yyyy-mm-dd HH:mm:ss).
所以我尝试编码并卡住.
所以,这是代码:
So, I already search on google and most of them using Java, there is one using Kotlin and often using different time format than what I used (yyyy-mm-dd HH:mm:ss).
So I tried to code and stuck.
So, here is the code :
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
fun main(args : Array<String>) {
// 2019-05-24 14:17:00 | 2019-09-13 14:15:51
val start = "2019-05-24 14:17:00"
val end = "2019-09-13 14:15:51"
daysBetweenDates(start, end)
}
fun daysBetweenDates(start: String, end: String) {
val mStart = LocalDateTime.parse(start)
val mEnd = LocalDateTime.parse(end)
val difference = ChronoUnit.DAYS.between(mStart, mEnd)
println("START => $mStart")
println("END => $mEnd")
println("DIFFERENCE => $difference days")
}
但是我遇到了一个错误:
But I got an error :
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-05-24 14:17:00' could not be parsed at index 10
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at java.time.LocalDateTime.parse(LocalDateTime.java:477)
at MainKt.daysBetweenDates(main.kt:16)
at MainKt.main(main.kt:11)
推荐答案
例如,您需要使用DateTimeFormatter
格式化日期,这样看起来就更少了:
You need to format the date using for example DateTimeFormatter
, so it would look like this more less:
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val mStart = LocalDateTime.parse(start, format)
当您的日期字符串不是parse方法要求的ISO格式时,就会发生这种情况.
It happens when your date string is not ISO format that is required by parse method.
这篇关于在Android Kotlin中查找日期之间的天差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文