function _formatNormalize ( formatter ) { if ( typeof formatter === 'function' ) { return formatter; } if ( typeof formatter !== 'string' ) { throw new TypeError ( 'formatter must be string or function' ) ; } if ( formatter === 'data' ) { formatter = 'yyyy-MM-dd' ; } else if ( formatter === 'datatime' ) { formatter = 'yyyy-MM-dd HH:mm:ss' ; } return ( dateInfo ) => { const { yyyy, MM , dd, HH , mm, ss, ms } = dateInfo; return formatter. replace ( 'yyyy' , yyyy) . replace ( 'MM' , MM ) . replace ( 'dd' , dd) . replace ( 'HH' , HH ) . replace ( 'mm' , mm) . replace ( 'ss' , ss) . replace ( 'ms' , ms) }
}
function formate ( date, formatter, isPad = false ) { formatter = _formatNormalize ( formatter) ; const dateInfo = { year : date. getFullYear ( ) , month : date. getMonth ( ) + 1 , date : date. getDate ( ) , hours : date. getHours ( ) , minutes : date. getMinutes ( ) , seconds : date. getSeconds ( ) , milliseconds : date. getMilliseconds ( ) } dateInfo. yyyy = isPad ? dateInfo. year. toString ( ) . padStart ( 4 , '0' ) : dateInfo. year; dateInfo. MM = isPad ? dateInfo. month. toString ( ) . padStart ( 2 , '0' ) : dateInfo. month; dateInfo. dd = isPad ? dateInfo. date. toString ( ) . padStart ( 2 , '0' ) : dateInfo. date; dateInfo. HH = isPad ? dateInfo. hours. toString ( ) . padStart ( 2 , '0' ) : dateInfo. hours; dateInfo. mm = isPad ? dateInfo. minutes. toString ( ) . padStart ( 2 , '0' ) : dateInfo. minutes; dateInfo. ss = isPad ? dateInfo. seconds. toString ( ) . padStart ( 2 , '0' ) : dateInfo. seconds; dateInfo. ms = isPad ? dateInfo. milliseconds. toString ( ) . padStart ( 3 , '0' ) : dateInfo. milliseconds; return formatter ( dateInfo) ;
}
let a = formate ( new Date ( ) , 'data' ) ;
let b = formate ( new Date ( ) , 'datatime' ) ;
let c = formate ( new Date ( ) , 'data' , true ) ;
let d = formate ( new Date ( ) , 'datatime' , true ) ;
let e = formate ( new Date ( ) , 'yyyy年MM月dd日 HH:mm:ss' , true ) ;
const f = formate ( new Date ( '2022/1/1' ) , ( dateInfo ) => {
const { year } = dateInfo;
const thisYear = new Date ( ) . getFullYear ( ) ;
if ( year < thisYear) {
return ` ${ thisYear - year} 年前 ` ;
} else if ( year > thisYear) {
return ` ${ year - thisYear} 年后 `
} else {
return ` 今年 `
}
} ) ; console. log ( a, b, c, d, e, f)