code
//日期戳轉日期字符串:yyyy-MM-dd HH:mm:ss export const formatDate = (v: string | number | Date) => { if (v == null) { return ''; } else { const dateObj = new Date(v); // 創建Date對象 const year = dateObj.getFullYear(); // 獲取年份 const month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 獲取月份,并補零 const day = ("0" + dateObj.getDate()).slice(-2); // 獲取日期,并補零 const hour = ("0" + dateObj.getHours()).slice(-2); // 獲取小時,并補零 const minute = ("0" + dateObj.getMinutes()).slice(-2); // 獲取分鐘,并補零 const second = ("0" + dateObj.getSeconds()).slice(-2); // 獲取秒,并補零 return `${year}-${month}-${day} ${hour}:${minute}:${second}`; // 返回轉換后的日期格式 } } //日期戳轉日期字符串:yyyy-MM-dd export const formatDateShort = (v: string | number | Date) => { let fullDateStr = formatDate(v); if (fullDateStr != '') { fullDateStr = fullDateStr.substring(0, 11); } return fullDateStr; } // 格式化日期 yyyy年-MM月-dd日 export const formatDateShortCN = (val: string | number | Date) => { const dateObj = new Date(val) const year = dateObj.getFullYear(); // 獲取年份 const month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 獲取月份,并補零 const day = ("0" + dateObj.getDate()).slice(-2); // 獲取日期,并補零 return year + '年-' + month + '月-' + day + '日'; } //獲取時間戳 export function getNowTimeSpan() { return new Date().getTime();//.toString() } //獲取時間戳 export function getDateTimeSpan(date: Date) { return date.getTime();//.toString() } //修改日期,增加或減少(負數)指定日期段,判斷閏2月 export const dateAdd = (date: string | number | Date, strInterval: string, num: number) => { //日期 var dt = new Date(date); //傳入日期轉日期戳 var dtstp = dt.getTime(); switch (strInterval) { case 'sec': return new Date(dtstp + (1000 * num));//秒 case 'min': return new Date(dtstp + (60000 * num));//分 case 'hour': return new Date(dtstp + (3600000 * num));//小時 case 'day': return new Date(dtstp + (86400000 * num));//天 case 'weekend': return new Date(dtstp + ((86400000 * 7) * num));//周 //季度(三個月) case 'quarter': let monthQ = (dt.getMonth()) + (num * 3); let dQ = dt.getDate(); //如果是2月,判斷28天還是29天。 let monthCal = (monthQ + 1) % 12; if (monthCal == 0) { //等于0,說明是12月。 monthCal = 12; } if (monthCal == 2 && dQ > 28) { let testDate = new Date(dt.getFullYear(), monthQ, 29); if (testDate.getDate() == 29) { dQ = 29; } else { dQ = 28; } } return new Date(dt.getFullYear(), monthQ, dQ, dt.getHours(), dt.getMinutes(), dt.getSeconds()); //月 case 'month': let month = (dt.getMonth()) + num; let d = dt.getDate(); //如果是2月,判斷28天還是29天。 let monthCal2 = (month + 1) % 12; if (monthCal2 == 0) { //等于0,說明是12月。 monthCal2 = 12; } if (monthCal2 == 2 && d > 28) { let testDate2 = new Date(dt.getFullYear(), month, 29); if (testDate2.getDate() == 29) { d = 29; } else { d = 28; } } return new Date(dt.getFullYear(), month, d, dt.getHours(), dt.getMinutes(), dt.getSeconds()); //年 case 'year': return new Date((dt.getFullYear() + num), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds()); } return dt; }
浙公網安備 33010602011771號