先提供2個方法,根據當前日期轉化年月日方法
export function formatDate(date) { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return [year, month, day].map(formatNumber).join('-'); } export function formatDateBegin(date) { const year = date.getFullYear(); const month = date.getMonth(); const day = date.getDate(); return [year, month, day].map(formatNumber).join('-'); }
提前N天或推后N天的方法,返回時間戳
/* *now 為當前時間new Date() *d為天數,提前3天,傳-3 * 推后3天,傳3 **/ export function defaulTime(now, d) { now.setHours(0); now.setMinutes(0); now.setSeconds(0); now.setDate(now.getDate() + d); now = now.getTime(); return now; }
console.log(defaulTime(new Date(),-24),defaulTime(new Date(),6)); //提前24天和推后6天,返回時間戳
提前N天或推后N天的方法,返回年月日,
注:我這個方法把當前時間的時分秒設為了0,如果不需要注釋即可
/* *now 為當前時間new Date() *d為天數,提前傳負數,推后傳正數 * 提前3天,傳-3 * 推后3天,傳3 **/ export function defaulTime2(now, d) { //把時分秒設置為0,不需要就直接注釋掉就好了 now.setHours(0); now.setMinutes(0); now.setSeconds(0); now.setDate(now.getDate() + d); now = formatDate(now); //用了上面轉年月日的方法
// now = now.toLocaleDateString(); //自帶的年月小於10時,沒有自動補0,所以用了自己的方法,看自己需要
return now; }
console.log(defaulTime2(new Date(),-24),defaulTime2(new Date(),6)); //提前24天和推后6天,返回日期
