相关文章推荐
正直的桔子  ·  kubectlコマンドで「certifica ...·  1 月前    · 
帅气的荔枝  ·  [Steam Remote Play] ...·  2 周前    · 
喝醉的毛豆  ·  网上办事_东莞市住房和城乡建设局·  9 月前    · 
风流倜傥的麦片  ·  广州首个共享草坪“志愿护绿驿站”正式开放 ...·  2 年前    · 
威武的蘑菇  ·  家长来信人民日报谈孩子教育:择校又远又贵又折 ...·  2 年前    · 
豪气的电影票  ·  遇到杀猪盘 被骗几十万 ...·  2 年前    · 
月球上的海豚  ·  网络安全的相关比赛有哪些?网友:不会真要破解 ...·  2 年前    · 
Code  ›  如何获取日期的剩余天数并打印小时、分钟和秒Java8开发者社区
string utc
https://cloud.tencent.com/developer/ask/sof/108831056
沉着的火车
2 年前
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
提问
问 如何获取日期的剩余天数并打印小时、分钟和秒Java8
Stack Overflow用户
提问于 2021-11-21 18:58:48
EN

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

"endValidityDate": "2021-11-18T22:59:59Z"

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

我现在得到的是:

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

DateTime.now().plusSeconds(172800)

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

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

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”。

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

val expireDate = LocalDateTime.now()
                   .plusSeconds(uiState.endValidityDate.timeLeft.toLong())
                   .toEpochSecond(ZoneOffset.UTC)
val currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)

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

val duration = Duration.ofSeconds(it)
binding.myTextView.text = String.format(
    "%02dh: %02dm: %02ds",
    duration.seconds / 3600,
    (duration.seconds % 3600) / 60,
    duration.seconds % 60,
)

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

00h: 33m: 50s

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

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

实现

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

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

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

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

注意:

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

1 848 0 票数 1
EN
java
android
date
kotlin
datetime

回答 1

Stack Overflow用户

回答已采纳

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

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

下面是一个Kotlin的例子:

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 ,可能如下所示:

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
 
推荐文章
正直的桔子  ·  kubectlコマンドで「certificate has expired or is not yet valid」エラーが出た話 #RaspberryPi - Qiita
1 月前
帅气的荔枝  ·  [Steam Remote Play] Streaming through Steam only works on WiFi / Multimedia and Games / Arch Linux F
2 周前
喝醉的毛豆  ·  网上办事_东莞市住房和城乡建设局
9 月前
风流倜傥的麦片  ·  广州首个共享草坪“志愿护绿驿站”正式开放 - 广州市人民政府门户网站
2 年前
威武的蘑菇  ·  家长来信人民日报谈孩子教育:择校又远又贵又折腾|家长|学校|孩子_新浪育儿_新浪网
2 年前
豪气的电影票  ·  遇到杀猪盘 被骗几十万 目前还在跟骗子联系,还想骗我的钱,如何骗回骗子的钱? - 知乎
2 年前
月球上的海豚  ·  网络安全的相关比赛有哪些?网友:不会真要破解支付宝证明技术吧! - 知乎
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号