milliseconds to time in javascript

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

    var 
             /**
             * Parses time in milliseconds to time structure
             * @param {Number} ms
             * @returns {Object} timeStruct
             * @return {Integer} timeStruct.d days
             * @return  {Integer} timeStruct.h hours
             * @return  {Integer} timeStruct.m minutes
             * @return  {Integer} timeStruct.s seconds
             */
            millisecToTimeStruct = function (ms) {
                var d, h, m, s;
                if (isNaN(ms)) {
                    return {};
                }
                d = ms / (1000 * 60 * 60 * 24);
                h = (d - ~~d) * 24;
                m = (h - ~~h) * 60;
                s = (m - ~~m) * 60;
                return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
            },
    
            toFormattedStr = function(tStruct){
               var res = '';
               if (typeof tStruct === 'object'){
                   res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
               }
               return res;
            };
    
    // client code:
    var
            ms = new Date().getTime(),
            timeStruct = millisecToTimeStruct(ms),
            formattedString = toFormattedStr(timeStruct);
    alert(formattedString);
    

提交回复
热议问题