From milliseconds to hour, minutes, seconds and milliseconds
Solution 1:
Here is how I would do it in Java:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
Solution 2:
Good question. Yes, one can do this more efficiently. Your CPU can extract both the quotient and the remainder of the ratio of two integers in a single operation. In <stdlib.h>
, the function that exposes this CPU operation is called div()
. In your psuedocode, you'd use it something like this:
function to_tuple(x):
qr = div(x, 1000)
ms = qr.rem
qr = div(qr.quot, 60)
s = qr.rem
qr = div(qr.quot, 60)
m = qr.rem
h = qr.quot
A less efficient answer would use the /
and %
operators separately. However, if you need both quotient and remainder, anyway, then you might as well call the more efficient div()
.
Solution 3:
Maybe can be shorter an more elegant. But I did it.
public String getHumanTimeFormatFromMilliseconds(String millisecondS){
String message = "";
long milliseconds = Long.valueOf(millisecondS);
if (milliseconds >= 1000){
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
int days = (int) (milliseconds / (1000 * 60 * 60 * 24));
if((days == 0) && (hours != 0)){
message = String.format("%d hours %d minutes %d seconds ago", hours, minutes, seconds);
}else if((hours == 0) && (minutes != 0)){
message = String.format("%d minutes %d seconds ago", minutes, seconds);
}else if((days == 0) && (hours == 0) && (minutes == 0)){
message = String.format("%d seconds ago", seconds);
}else{
message = String.format("%d days %d hours %d minutes %d seconds ago", days, hours, minutes, seconds);
}
} else{
message = "Less than a second ago.";
}
return message;
}