计算差值(这其中添加了带小时的计算)
data() {
return {
startDateString: "2021-01-01 00:00:00",
endDateString: "2021-10-02 10:00:00",
};
},
created() {
this.getRemainingTime();
console.log(this.getRemainingTime());
},
methods: {
getRemainingTime() {
const startDate = new Date(this.startDateString);
const endDate = new Date(this.endDateString);
let timeDiff = endDate.getTime() - startDate.getTime();
const oneDay = 24 * 60 * 60 * 1000;
let remainingMonths = 0;
let remainingDays = 0;
let remainingHours = 0;
while (startDate < endDate) {
const lastDayOfMonth = new Date(
startDate.getFullYear(),
startDate.getMonth() + 1,
0
);
const daysInMonth = lastDayOfMonth.getDate();
const oneMonth = daysInMonth * oneDay;
if (timeDiff >= oneMonth) {
timeDiff -= oneMonth;
remainingMonths++;
} else {
break;
}
startDate.setMonth(startDate.getMonth() + 1, 1);
}
remainingDays = Math.floor(timeDiff / oneDay);
remainingHours = Math.floor((timeDiff % oneDay) / (60 * 60 * 1000));
return {
remainingMonths,
remainingDays,
remainingHours,
};
},
},
打印结果