从毫秒到小时,分钟,秒和毫秒

Mad*_*ern 38 algorithm date pseudocode

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

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)
Run Code Online (Sandbox Code Playgroud)

我敢肯定必须能够做得更聪明/更优雅/更快/更紧凑.

Ale*_*x W 112

以下是我在Java中的表现:

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);
Run Code Online (Sandbox Code Playgroud)

  • `长毫秒 = 12884983; System.out.println(((millis / (1000 * 60)) % 60)); System.out.println(java.util.concurrent.TimeUnit.MILLISECONDS.toMinutes(millis));`输出:34 | 214 (10认同)
  • 值得在java中使用TimeUnit来使代码更具可读性. (3认同)

thb*_*thb 7

好问题.是的,人们可以更有效地做到这一点.您的CPU可以在单个操作中提取两个整数的比率的商和余数.在<stdlib.h>,调用公开此CPU操作的函数div().在你的伪代码中,你会使用这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

效率较低的答案将分别使用/%运算符.但是,无论如何,如果你需要商和余数,那么你也可以称之为效率更高div().


bhe*_*ker 5

也许可以更短更优雅.但我做到了.

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;
}
Run Code Online (Sandbox Code Playgroud)