JS将毫秒转为时分秒

// 将毫秒转为时分秒
function transTimestampToTime(value) {
    if (value === 0 || value < 1000) return '0秒';
    var timestamp = parseInt(value) / 1000; // 毫秒转秒
    // 小时取余数
    const remainder = timestamp % 3600
    // 时、分、秒
    let hour, minute, second;
    if (remainder === 0) { // 整除 小时
        hour = parseInt(timestamp / 3600);
    } else {
        hour = parseInt(timestamp / 3600);
        let remainderMinute = remainder % 60;
        if (remainderMinute === 0) { // 整除 分钟
            minute = parseInt(remainder / 60);
        } else {
            minute = parseInt(remainder / 60);
            second = parseInt(remainderMinute);
        }
    }
    let text = '';
    if (hour > 0) {
        text += hour + '时';
    }
    if (minute > 0) {
        text += minute + '分';
    }
    if (second > 0) {
        text += second + '秒';
    }
    return text;
}

// 示例
let timestamp = 2851630845;
let timeString = transTimestampToTime(timestamp);
console.log(timeString); // 输出:792时7分10秒
let index = timeString.indexOf('时')
console.log(timeString.slice(0, index)); // 输出:792

你可能感兴趣的:(前端,javascript)