1.获取任意格式的日期
function getFormattedDate(timestamp, format) {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const pad = (num) => (num < 10 ? '0' + num : num);
return format
.replace('YYYY', year)
.replace('MM', pad(month))
.replace('DD', pad(day))
.replace('HH', pad(hours))
.replace('mm', pad(minutes))
.replace('ss', pad(seconds));
}
// 使用示例:
const timestamp = 1609365200000;
const formattedDate1 = getFormattedDate(timestamp, 'YYYY-MM-DD HH:mm:ss');
const formattedDate2 = getFormattedDate(timestamp, 'YYYY年MM月DD日 HH时mm分ss秒');
console.log(formattedDate1);
console.log(formattedDate2);
2.求时间间隔
monthsBetween(date1, date2) {
console.log("date1, date2",date1, date2)
let months
months = (date2.getFullYear() - date1.getFullYear()) * 12
months -= date1.getMonth()
months += date2.getMonth()
return months <= 0 ? 0 : months
},
// 示例使用:
const date1 = new Date('2023-01-01');
const date2 = new Date('2023-04-01');
console.log(monthsBetween(date1, date2)); // 输出:3