任务是:
The output should look like this (it is a good idea to echo back the input): You entered 500,000 seconds, which is 5 days, 18 hours, 53 minutes and 20 seconds. (5 days 18:53:20 hours)
我该怎么做?最简单的理解和执行方法是什么?
讲师还说“没有硬编码”,我不太确定这是什么,但我认为他希望我们为它们分配常量。
最佳答案
使用内置 <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html" rel="noreferrer noopener nofollow">TimeUnit</a>
的示例.
long uptime = System.currentTimeMillis();
long days = TimeUnit.MILLISECONDS
.toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS
.toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS
.toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS
.toSeconds(uptime);
关于Java:将秒转换为分钟、小时和天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25903354/