1. 计算时差
function dateDifference(faultDate, completeTime) {
if (!faultDate || !completeTime) return null
let stime = new Date(faultDate).getTime()
let etime = new Date(completeTime).getTime()
let diffTime = etime - stime // 两个时间戳相差的毫秒数
let days = Math.floor(diffTime / (24 * 3600 * 1000))
// 计算出小时数
let leave1 = diffTime % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
let hours = Math.floor(leave1 / (3600 * 1000))
// 计算相差分钟数
let leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
let minutes = Math.floor(leave2 / (60 * 1000))
let time = `${days}天 ${hours}时 ${minutes}分`
// var h = Math.floor(result / 3600);
// var m = Math.floor((result / 60 % 60));
// var s = Math.floor((result % 60));
return { time, days, hours, minutes, diffTime }
}
2. 判断是否为闰年
function isLeapYear(year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
3. 获取指定年月的天数
function getDayNum(year, month) {
year = parseInt(year);
month = parseInt(month);
if ([1, 3, 5, 7, 8, 10, 12].indexOf(month) > -1) {
return 31;
} else if ([4, 6, 9, 11].indexOf(month) > -1) {
return 30;
} else if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 29;
} else {
return 28;
}
}
4. 毫秒转换为时分秒格式
function milliTrans(milli) {
let time = milli / 1000;
let seconds = parseInt(time % 60);
if (seconds < 10) {
seconds = '0' + seconds;
}
let minutes = parseInt((time / 60) % 60);
if (minutes < 10) {
minutes = '0' + minutes;
}
let hours = parseInt((time / 3600) % 60);
if (hours > 0) {
console.log(hours);
return (
hours +
':' +
(minutes != 0 ? minutes : '00') +
':' +
(seconds != 0 ? seconds : '00')
);
} else if (minutes > 0) {
console.log(minutes);
return minutes + ':' + (seconds != 0 ? seconds : '00');
} else {
return seconds + '秒';
}
}