定时器 – 倒计时并以特定格式显示结果

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

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

“你有:#d#days,#h#hours,#m#minutes to die”

然后只显示:

“你有1天,13小时,43分钟就死了”

但是如果你将格式设置为:

“你有:#h#hours,#m#minutes to die”

然后我需要显示:

“你有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)); } 

并且……有更好的方法吗?

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd"); String text = date.toString(formatter); LocalDate date = LocalDate.parse(text, formatter); 

更多信息在这里

或者,如果你不在这里使用java8

乔达时间

如果您的目标是拼写出“1天,13小时和43分钟”的字样,那么Joda-Time就有一个完全符合该目的的类: PeriodFormatterBuilder 。 尝试编写自己的类更容易使用该类。 请参阅其他答案中的示例,例如本章和本章 。

java.time。*

Java 8中新的java.time。*包可能有类似的东西,因为它受到了Joda-Time的启发。 也许是java.time.format包中的DateTimeFormatterBuilder类。