val expireDate = LocalDateTime.now()
.plusSeconds(uiState.endValidityDate.timeLeft.toLong())
.toEpochSecond(ZoneOffset.UTC)
val currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)
fun main() {
val utc = ZoneId.of("UTC")
val now = ZonedDateTime.now(utc)
val twoDaysFromNow = now.plusDays(2)
val remainingDays = ChronoUnit.DAYS.between(now, twoDaysFromNow)
println(
String.format("%d days", remainingDays)
}
输出:
2 days
补充:
由于我不清楚您试图使用什么数据类型来计算到有效期结束前的时间,所以您必须在
中选择在问题
中提供更详细的信息,还是使用下列
fun
之一:
ZonedDateTime
传递
private fun getRemainingTime(endValidityDate: ZonedDateTime): String {
// get the current moment in time as a ZonedDateTime in UTC
val now = ZonedDateTime.now(ZoneId.of("UTC"))
// calculate the difference directly
val timeLeft = Duration.between(now, endValidityDate)
// return the messages depending on hours left
return if (timeLeft.toHours() >= 24) "${timeLeft.toDays()} days"
else String.format("%02dh: %02dm: %02ds",
timeLeft.toHours(),
timeLeft.toMinutes() % 60,
timeLeft.toSeconds() % 60)
}
Instant
传递
private fun getRemainingTime(endValidityDate: Instant): String {
// get the current moment in time, this time as an Instant directly
val now = Instant.now()
// calculate the difference
val timeLeft = Duration.between(now, endValidityDate)
// return the messages depending on hours left
return if (timeLeft.toHours() >= 24) "${timeLeft.toDays()} days"
else String.format("%02dh: %02dm: %02ds",
timeLeft.toHours(),
timeLeft.toMinutes() % 60,
timeLeft.toSeconds() % 60)
}
String
直接传递
private fun getRemainingTime(endValidityDate: String): String {
// get the current moment in time as a ZonedDateTime in UTC
val now = ZonedDateTime.now(ZoneId.of("UTC"))
// parse the endValidtyDate String
val then = ZonedDateTime.parse(endValidityDate)
// calculate the difference
val timeLeft = Duration.between(now, then)
// return the messages depending on hours left