我需要从毫秒到表示相同时间量的元组(小时、分钟、秒、毫秒)。例如:
10799999ms = 2h 59m 59s 999ms
下面的伪代码是我唯一能想到的东西:
# The division operator below returns the result as a rounded down integer
function to_tuple(x):
h = x / (60*60*1000)
x = x - h*(60*60*1000)
m = x / (60*1000)
x = x - m*(60*1000)
s = x / 1000
x = x - s*1000
return (h,m,s,x)我相信一定有可能做得更聪明/更优雅/更快/更紧凑。
发布于 2012-06-04 05:38:45
下面是我在Java中的实现方法:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);发布于 2012-06-04 05:39:51
问得好。是的,人们可以更有效地做到这一点。您的CPU可以在一次操作中同时提取两个整数之比的商和余数。在<stdlib.h>中,公开此CPU操作的函数称为div()。在你的psuedocode中,你可以这样使用它:
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一种效率较低的答案是分别使用/和%运算符。但是,如果您同时需要商和余数,那么您不妨调用效率更高的div()。
发布于 2015-07-23 22:59:25
也许可以更短一点,更优雅一点。但我做到了。
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;
}https://stackoverflow.com/questions/10874048
复制相似问题