1. 程式人生 > 其它 >js把秒數轉換為HH:MM:SS及時分秒格式

js把秒數轉換為HH:MM:SS及時分秒格式


    /**
     * 轉為HH:MM:SS
     * @param second
     * @returns {string}
     * @private
     */
      var _showTime = function (second) {
        if (second < 60) {
            if (second < 10) {
                return "00:00:0" + second;
            } else {
                return "00:00:" + second;
            }
        } else {
            var min_total = Math.floor(second / 60);	// 分鐘
            var sec = Math.floor(second % 60);	// 餘秒
            if (min_total < 60) {
                if (min_total < 10) {
                    if (sec < 10) {
                        return "00:0" + min_total + ":0" + sec;
                    } else {
                        return "00:0" + min_total + ":" + sec;
                    }
                } else {
                    if (sec < 10) {
                        return "00:" + min_total + ":0" + sec;
                    } else {
                        return "00:" + min_total + ":" + sec;
                    }
                }
            } else {
                var hour_total = Math.floor(min_total / 60);	// 小時數
                if (hour_total < 10) {
                    hour_total = "0" + hour_total;
                }
                var min = Math.floor(min_total % 60);	// 餘分鐘
                if (min < 10) {
                    min = "0" + min;
                }
                if (sec < 10) {
                    sec = "0" + sec;
                }
                return hour_total + ":" + min + ":" + sec;
            }
        }
    }


    /**
     * 轉換時間格式為xx小時xx分xx秒
     * @param time HH:MM:SS
     */
    function changeTimeFormat(time) {
        var timeList = [];
        timeList = time.split(":");
        console.log(timeList)
        if (timeList[0] == '00') {
            if (timeList[1] == '00') {
                return timeList[2] + "秒";
            } else {
                if (timeList[2] == '00') {
                    return timeList[1] + "分";
                } else {
                    return timeList[1] + "分" + timeList[2] + "秒";
                }
            }
        } else {
            if (timeList[1] == '00') {
                if (timeList[2] == '00') {
                    return timeList[0] + "小時";
                } else {
                    return timeList[0] + "小時" + timeList[2] + "秒";
                }
            } else {
                if (timeList[2] == '00') {
                    return timeList[0] + "小時" + timeList[1] + "分";
                } else {
                    return timeList[0] + "小時" + timeList[1] + "分" + timeList[2] + "秒";
                }
            }
        }
    }