首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从毫秒到小时、分钟、秒和毫秒

从毫秒到小时、分钟、秒和毫秒
EN

Stack Overflow用户
提问于 2012-06-04 05:22:32
回答 10查看 115.9K关注 0票数 47

我需要从毫秒到表示相同时间量的元组(小时、分钟、秒、毫秒)。例如:

10799999ms = 2h 59m 59s 999ms

下面的伪代码是我唯一能想到的东西:

代码语言:javascript
复制
# 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)

我相信一定有可能做得更聪明/更优雅/更快/更紧凑。

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2012-06-04 05:38:45

下面是我在Java中的实现方法:

代码语言:javascript
复制
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);
票数 138
EN

Stack Overflow用户

发布于 2012-06-04 05:39:51

问得好。是的,人们可以更有效地做到这一点。您的CPU可以在一次操作中同时提取两个整数之比的商和余数。在<stdlib.h>中,公开此CPU操作的函数称为div()。在你的psuedocode中,你可以这样使用它:

代码语言:javascript
复制
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()

票数 7
EN

Stack Overflow用户

发布于 2015-07-23 22:59:25

也许可以更短一点,更优雅一点。但我做到了。

代码语言:javascript
复制
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;
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10874048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档