java—如何获得毫秒到小时、分钟、秒和剩余毫秒

twh00eeo  于 2021-07-05  发布在  Java
关注(0)|答案(2)|浏览(469)

好的,我最近在一周前开始用java编程,我正在尝试编写一个程序,它将花费毫秒,给我小时、分钟、秒和剩余的毫秒。现在我把大部分都记下来了,只是出于某种原因,给我的数字都是错的。我应该得到2小时46分40秒123毫秒。但我得到的却是2小时2分钟3秒123毫秒。
这是我的密码

int beginning = 10000123; //beginning is the starting number of milli seconds
   int hours = beginning/3600000;
   int rSecs = beginning%1000; //r = remaining
   int minutes = rSecs/60;
   int seconds = rSecs%60;
   int milliSecs = rSecs%1000;

   System.out.println("Lab03, 100 Point Version\n");
   System.out.println("Starting Milliseconds" + beginning); 
   System.out.println("Hours:" + hours);
   System.out.println("Minutes:" + minutes);
   System.out.println("Seconds:" + seconds);
   System.out.println("Milli Seconds:" +  milliSecs);

谢谢你的帮助!

elcex8rz

elcex8rz1#

如果您想避免使用幻数并采用更面向对象的方法,那么可以使用duration类。

Duration duration = Duration.ofMillis(10000123);
                long hours = duration.toHours();
                duration = duration.minusHours(hours);
                long minutes = duration.toMinutes();
                duration = duration.minusMinutes(minutes);
                long seconds = duration.getSeconds();
                duration = duration.minusSeconds(seconds);
                long milliSec = duration.toMillis();
bjg7j2ky

bjg7j2ky2#

你需要模化 3600000 对于剩余的毫秒

int hours = beginning/3600000;
int rMiliSecs = beginning%3600000;

因为它是毫秒,所以你需要除以60000(1米->60秒->60000毫秒)来表示分钟,再除以60000来得到剩余的时间

int minutes = rMiliSecs/60000;
rMiliSecs = rMiliSecs%60000;

然后除以1000表示秒,再除以1000(1s->1000ms)表示剩余毫秒

int seconds = rMiliSecs/1000;
int milliSecs = rMiliSecs%1000;

相关问题