milliseconds to time in javascript

后端 未结 18 2163
遇见更好的自我
遇见更好的自我 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: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"

提交回复
热议问题