Reputation: 35
Ok, so I've recently started programming in java about a week ago, and I'm attempting to write a program that will take milliseconds and give me hours, minutes, seconds, and remaining milliseconds. Now I've got most of it down its just for some reason, giving me numbers that are off. I should be getting 2hrs, 46 min, 40 seconds, and 123 milliseconds. But instead I'm getting 2hrs, 2min, 3secs, and 123 milliseconds.
Heres my code
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);
Thanks for any and all help!
Upvotes: 1
Views: 792
Reputation: 627
If you want to avoid the magic numbers and do a more OO approach you can use the Duration class.
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();
Upvotes: 0
Reputation: 18410
You need to modulo by 3600000
for remaining milli second
int hours = beginning/3600000;
int rMiliSecs = beginning%3600000;
Since it millisecond you need to divide by 60000(1m-> 60s -> 60000ms) for minute and modulo by 60000 to get remainings
int minutes = rMiliSecs/60000;
rMiliSecs = rMiliSecs%60000;
Then divide by 1000 for the second and modulo by 1000(1s -> 1000ms) for remaining millisecond
int seconds = rMiliSecs/1000;
int milliSecs = rMiliSecs%1000;
Upvotes: 1