首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获取日期的剩余天数并打印小时、分钟和秒Java8

如何获取日期的剩余天数并打印小时、分钟和秒Java8
EN

Stack Overflow用户
提问于 2021-11-21 18:58:48
回答 1查看 848关注 0票数 1

例如,我从服务器获得了一个UTC日期

代码语言:javascript
运行
复制
"endValidityDate": "2021-11-18T22:59:59Z"

我想知道从现在起计算剩余天数的最佳方法是什么。

我现在得到的是:

从现在开始,我将创建一个为期两天的约会,因为:

代码语言:javascript
运行
复制
DateTime.now().plusSeconds(172800)

我将其解析为一个DateTime joda,如果您这样说的话,我可以使用其他。

在不同的日子里,我就是这样做的

代码语言:javascript
运行
复制
val diff = endValidityDate.toDate().time - Date().time
val daysRemaining = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS)
return if (daysRemaining > 1) "$daysRemaining days}"
       else TimeUnit.DAYS.convert(diff, TimeUnit.SECONDS).toString()

我想要实现的情况是:

如果剩余天数超过一天(24小时),则打印“剩余2天”,而不是显示"1天剩余“,然后添加一个计时器,如下所示:

“0h43m3”。

为了完成计时器,我只是减去现在剩下的时间

代码语言:javascript
运行
复制
val expireDate = LocalDateTime.now()
                   .plusSeconds(uiState.endValidityDate.timeLeft.toLong())
                   .toEpochSecond(ZoneOffset.UTC)
val currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)

每一秒钟我都会像这样打印出来:

代码语言:javascript
运行
复制
val duration = Duration.ofSeconds(it)
binding.myTextView.text = String.format(
    "%02dh: %02dm: %02ds",
    duration.seconds / 3600,
    (duration.seconds % 3600) / 60,
    duration.seconds % 60,
)

但我没有得到这两天,我只是作为一个产出:

代码语言:javascript
运行
复制
00h: 33m: 50s

所以,我在这里遇到了一些问题,例如:

这是一个最佳的解决方案吗?如果没有,你能描述一个更好的我可以实现我的目标吗?为什么我的计时器是用00h: 13m: 813s显示的?我是做错了正则表达式,还是因为epochSeconds?

实现

当试图将UTC日期打印到设备时,给出一个UTC数据,那么它应该遵循以下规则。

1.-如果剩余天数超过1天,则打印“剩余N天”

2.-如果剩下的天数是<= 1,那么打印一个计时器(它已经完成了,关键是如何正确地打印它)。

  • 最小1位数(0h2m 1s)
  • 最大2位数(1h 23m3s)

注意:

我使用的是Java 8,如果这是问题所在,我也可以改变使用millis而不是epochSeconds的倒计时方式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-21 20:01:54

现在和将来的日期时间都可以使用ZonedDateTime来完成,然后计算一个Duration.between,而不是先计算剩余的秒,然后使用Duration.ofSeconds()

下面是一个Kotlin的例子:

代码语言:javascript
运行
复制
fun main() {
    val utc = ZoneId.of("UTC")
    val now = ZonedDateTime.now(utc)
    val twoDaysFromNow = now.plusDays(2)
    
    val remaining = Duration.between(now, twoDaysFromNow)
    
    println(
        String.format("%02dh: %02dm: %02ds",
                        remaining.seconds / 3600,
                        (remaining.seconds % 3600) / 60,
                        remaining.seconds % 60
                     )
    )
}

输出:48h: 00m: 00s

如果您只对剩下的一整天感兴趣,那么请考虑使用ChronoUnit.DAYS.between,可能如下所示:

代码语言:javascript
运行
复制
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 传递

代码语言:javascript
运行
复制
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 传递

代码语言:javascript
运行
复制
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 直接传递

代码语言:javascript
运行
复制
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
    return if (timeLeft.toHours() >= 24) "${timeLeft.toDays()} days"
    else String.format("%02dh: %02dm: %02ds",
                        timeLeft.toHours(),
                        timeLeft.toMinutes() % 60,
                        timeLeft.toSeconds() % 60)
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70057662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档