From milliseconds to hour, minutes, seconds and milliseconds

前端 未结 9 1831
失恋的感觉
失恋的感觉 2020-12-07 21:22

I need to go from milliseconds to a tuple of (hour, minutes, seconds, milliseconds) representing the same amount of time. E.g.:

10799999ms = 2h 59m 59s 999ms

相关标签:
9条回答
  • 2020-12-07 21:49
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.TimeUnit;
    
    public class MyTest {
    
        public static void main(String[] args) {
            long seconds = 360000;
    
            long days = TimeUnit.SECONDS.toDays(seconds);
            long hours = TimeUnit.SECONDS.toHours(seconds - TimeUnit.DAYS.toSeconds(days));
    
            System.out.println("days: " + days);
            System.out.println("hours: " + hours);
        }
    }
    
    0 讨论(0)
  • 2020-12-07 21:51

    not really eleganter, but a bit shorter would be

    function to_tuple(x):
       y = 60*60*1000
       h = x/y
       m = (x-(h*y))/(y/60)
       s = (x-(h*y)-(m*(y/60)))/1000
       mi = x-(h*y)-(m*(y/60))-(s*1000)
    
       return (h,m,s,mi)
    
    0 讨论(0)
  • 2020-12-07 21:53

    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);
    
    0 讨论(0)
提交回复
热议问题