【问题标题】:Timer - counting down and displaying result in specific format [duplicate]计时器 - 倒计时并以特定格式显示结果[重复]
【发布时间】:2014-02-15 12:59:12
【问题描述】:

我有计数器,你设置一个日期,然后你可以得到这个日期的时间,但我需要以选择的格式显示它。

例如: 如果我还剩 1 天 13 小时 43 分 30 秒,并将格式设置为:

“你还有:#d# 天,#h# 小时,#m# 分钟死亡”

然后只显示:

“你还有 1 天 13 小时 43 分钟死”

但如果你将格式设置为:

“你还有:#h# 小时,#m# 分钟死亡”

那我需要显示:

“你还有 37 小时 43 分钟的时间去死”

(所以缺少的类型(天)被转换为其他(小时))


我有这个代码: PS:S、M、H、D、W 以毫秒为单位,分钟以毫秒为单位……

public static String getTimerData(long time, String format) {
    int seconds = -1, minutes = -1, hours = -1, days = -1, weeks = -1;
    if (format.contains("#s#")) {
        seconds = (int) (time / S);
    }
    if (format.contains("#m#")) {
        if (seconds == -1) {
            minutes = (int) (time / M);
        } else {
            minutes = (seconds / 60);
            seconds %= 60;
        }
    }
    if (format.contains("#h#")) {
        if (minutes == -1) {
            hours = (int) (time / H);
        } else {
            hours = (minutes / 60);
            minutes %= 60;
        }
    }
    if (format.contains("#d#")) {
        if (hours == -1) {
            days = (int) (time / D);
        } else {
            days = (hours / 24);
            hours %= 24;
        }
    }
    if (format.contains("#w#")) {
        if (days == -1) {
            weeks = (int) (time / W);
        } else {
            weeks = (days / 7);
            days %= 7;
        }
    }
    return format.replace("#w#", Integer.toString(weeks)).replace("#d#", Integer.toString(days)).replace("#h#", Integer.toString(hours)).replace("#m#", Integer.toString(minutes)).replace("#s#", Integer.toString(seconds));
}

还有...有更好的方法吗?

【问题讨论】:

    标签: java date countdown


    【解决方案1】:
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
    String text = date.toString(formatter);
    LocalDate date = LocalDate.parse(text, formatter);
    

    更多信息here

    或者,如果你没有使用 java8 here

    【讨论】:

    • 我需要一些东西而不使用其他 API。 (我写了一些小东西,只是作为附件)
    • Java 8 不是“其他 API”。
    • Ach...我认为这是“joda-time”。但我必须使用 java 7 ;/
    • @user2250333 它存在于 java7 以及 java6、java 5 等中
    • @MartinAsenov 但这只是显示一个日期,我需要一些倒计时的东西,例如:You have 3 hours and 30 minutes to die,或You have 210 minutes to die,其中首先使用You have #h# hours and #m# minutes to die,其次使用You have #m# minutes to die 模式。
    【解决方案2】:

    乔达时间

    如果您的目标是拼出“1 天 13 小时 43 分钟”的单词,那么 Joda-Time 有一个专门用于该目的的类:PeriodFormatterBuilder。使用该类比尝试编写自己的类更容易。请参阅其他答案中的示例,例如 this onethis one

    java.time.*

    Java 8 中的新 java.time.* package 可能有类似的东西,因为它的灵感来自 Joda-Time。可能是java.time.format package 中的DateTimeFormatterBuilder 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2018-03-28
      • 1970-01-01
      相关资源
      最近更新 更多