如何获得两次约会之间的差异(jetpackcompose/kotlin)



我必须计算用户通过DatePicker选择的日期与当前日期之间还剩多少天

我试着写这样的东西:

val simpleDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
val date = simpleDate.parse(event!!.date!!)
val diff = Duration.between(LocalDate.now(), date.toInstant())
val leftDays = diff.toDays()

我认为,过时(SimpleDateFormat,'Date'(和现代(LocalDate(API的组合不是最佳的:

我会在这里使用普通的java.time,因为…

  • 您显然可以在应用程序中使用它
  • 它有一个特定的类,用于您在问题中显示的模式的日期时间Strings:OffsetDateTime
  • 有一个java.time.Duration你试过用

这里有一个例子:

fun main(args: Array<String>) {
// example input, some future datetime
val input = "2022-12-24T13:22:51.837Z"
// parse that future datetime
val offsetDateTime = OffsetDateTime.parse(input)
// build up a duration between the input and now, use the same class
val duration = Duration.between(OffsetDateTime.now(), offsetDateTime)
// get the difference in full days
val days = duration.toDays()
// print the result as "days left"
println("$days days left")
}

输出:

110 days left

如果您没有收到日期时间,而是收到一个没有时间的日期(仅为年月日(,则使用LocalDate并计算ChronoUnit.DAYS.between(today, futureDate)

fun main(args: Array<String>) {
// example input, some future date
val input = "2022-12-24"
// parse that
val futureDate = LocalDate.parse(input)
// get the difference in full days
val days = ChronoUnit.DAYS.between(LocalDate.now(), futureDate)
// print the result
println("$days days left")
}

输出(再次(:

110 days left

尝试以下代码-

val previousTimeDouble: Double = previousTime.toDouble()
val nowTimeDouble: Double = System.currentTimeMillis().toDouble()
val dateNowString: String = dateNow.toString();
val time: Long = (nowTimeDouble - previousTimeDouble).toLong()
val difference: String= differenceBetweenTwoTimes(time)
Log.d("difference", difference)

将时差转换为单位的功能-

fun differenceBetweenTwoTimes(time: Long): String {
var x: Long = time / 1000
var seconds = x % 60
x /= 60
var minutes = x % 60
x /= 60
var hours = (x % 24).toInt()
x /= 24
var days = x
return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}

相关内容

  • 没有找到相关文章

最新更新