milliseconds to time in javascript

后端 未结 18 2102
遇见更好的自我
遇见更好的自我 2020-12-02 12:16

I have this function which formats seconds to time

 function secondsToTime(secs){
    var hours = Math.floor(secs / (60 * 60));
    var divisor_for_minutes          


        
相关标签:
18条回答
  • 2020-12-02 12:29

    This worked for me:

    var dtFromMillisec = new Date(secs*1000);
    var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
    

    JSFiddle

    0 讨论(0)
  • 2020-12-02 12:33

    Prons:

    • simple and clean code; easy to modify for your needs
    • support any amount of hours (>24 hrs is ok)
    • format time as 00:00:00.0

    You can put it into a helper file

    export const msecToTime = ms => {
      const milliseconds = ms % 1000
      const seconds = Math.floor((ms / 1000) % 60)
      const minutes = Math.floor((ms / (60 * 1000)) % 60)
      const hours = Math.floor((ms / (3600 * 1000)) % 3600)
      return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
        seconds < 10 ? '0' + seconds : seconds
      }.${milliseconds}`
    }
    
    0 讨论(0)
  • 2020-12-02 12:38

    Not to reinvent the wheel, here is my favourite one-liner solution:

    /**
     * Convert milliseconds to time string (hh:mm:ss:mss).
     *
     * @param Number ms
     *
     * @return String
     */
    function time(ms) {
        return new Date(ms).toISOString().slice(11, -1);
    }
    
    console.log( time(12345 * 1000) );  // "03:25:45.000"

    Method Date.prototype.toISOString() returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. This method is supported in all modern browsers (IE9+) and JavaScript engines.


    UPDATE: The solution above is always limited to range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). To make it working with any input value, I have extended it into a nice universal prototype method:

    /**
     * Convert (milli)seconds to time string (hh:mm:ss[:mss]).
     *
     * @param Boolean isSec
     *
     * @return String
     */
    Number.prototype.toTime = function(isSec) {
        var ms = isSec ? this * 1e3 : this,
            lm = ~(4 * !!isSec),  /* limit fraction */
            fmt = new Date(ms).toISOString().slice(11, lm);
    
        if (ms >= 8.64e7) {  /* >= 24 hours */
            var parts = fmt.split(/:(?=\d{2}:)/);
            parts[0] -= -24 * (ms / 8.64e7 | 0);
            return parts.join(':');
        }
    
        return fmt;
    };
    
    console.log( (12345 * 1000).toTime()     );  // "03:25:45.000"
    console.log( (123456 * 789).toTime()     );  // "27:03:26.784"
    console.log(  12345.       .toTime(true) );  // "03:25:45"
    console.log(  123456789.   .toTime(true) );  // "34293:33:09"

    0 讨论(0)
  • 2020-12-02 12:38

    try this function :-

    function msToTime(ms) {
      var d = new Date(null)
      d.setMilliseconds(ms)
      return d.toLocaleTimeString("en-US")
    }
    
    var ms = 4000000
    alert(msToTime(ms))

    0 讨论(0)
  • 2020-12-02 12:38

    An Easier solution would be the following:

    var d = new Date();
    var n = d.getMilliseconds(); 
    
    0 讨论(0)
  • 2020-12-02 12:39

    Editing RobG's solution and using JavaScript's Date().

    function msToTime(ms) {
    
        function addZ(n) {
            return (n<10? '0':'') + n;
        }
        var dt = new Date(ms);
        var hrs = dt.getHours();
        var mins = dt.getMinutes();
        var secs = dt.getSeconds();
        var millis = dt.getMilliseconds();
    
        var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
        return tm;
    }
    
    0 讨论(0)
提交回复
热议问题