获取昨天、今天、明天
快速获取相对日期的实用方法。
基础实现
// 获取今天
const today = new Date();
// 获取昨天
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
// 获取明天
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// 获取 N 天前的日期
function getDateDaysAgo(days) {
const date = new Date();
date.setDate(date.getDate() - days);
return date;
}
// 获取 N 天后的日期
function getDateDaysFrom(days) {
const date = new Date();
date.setDate(date.getDate() + days);
return date;
}
格式化输出
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
console.log('昨天:', formatDate(getDateDaysAgo(1)));
console.log('今天:', formatDate(new Date()));
console.log('明天:', formatDate(getDateDaysFrom(1)));
获取本周/上周/下周
// 获取本周周一
function getWeekStart(date = new Date()) {
const day = date.getDay();
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
const monday = new Date(date);
monday.setDate(diff);
monday.setHours(0, 0, 0, 0);
return monday;
}
// 获取上周周一
function getLastWeekStart() {
const lastWeek = new Date();
lastWeek.setDate(lastWeek.getDate() - 7);
return getWeekStart(lastWeek);
}