简单来说,就是计算两个时间点之间的年、月、日、时、分、秒这些的差距
let diffBetweenTimestamps = (timestamp1, timestamp2) => {return {years:yearsmonths: months,days: days,hours: hours,minutes: minutes,seconds: seconds};
}
let timestamp1 = 1629216000000;
let timestamp2 = 1675228800000;
let diff = diffBetweenTimestamps(timestamp1, timestamp2);
console.log(diff);
这道题的解答如下:
let diffBetweenTimestamps = (timestamp1, timestamp2) => {let date1 = new Date(timestamp1);let date2 = new Date(timestamp2);if (date1 > date2) {[date1, date2] = [date2, date1];}let years = date2.getFullYear() - date1.getFullYear();let months = date2.getMonth() - date1.getMonth();let days = date2.getDate() - date1.getDate();if (days < 0) {months--;let prevMonth = (date1.getMonth() + 11) % 12; let prevYear = date1.getFullYear() - Math.floor((date1.getMonth() + 1) / 12);let prevDate = new Date(prevYear, prevMonth + 1, 0).getDate();days += prevDate;}if (months < 0) {years--;months += 12;}let hours = date2.getHours() - date1.getHours();let minutes = date2.getMinutes() - date1.getMinutes();let seconds = date2.getSeconds() - date1.getSeconds();if (minutes < 0) {hours--;minutes += 60;}if (seconds < 0) {minutes--;seconds += 60;}return {years: years,months: months,days: days,hours: hours,minutes: minutes,seconds: seconds};
};
let timestamp1 = 1629216000000;
let timestamp2 = 1675228800000;
let diff = diffBetweenTimestamps(timestamp1, timestamp2);
console.log(diff);