const REGEX_FORMAT = /YYYY|M|D|dddd|HH|mm/g ; const MS_A_DAY = 24 * 60 * 60 * 1000 ; const MS_A_WEEK = MS_A_DAY * 7 ; export type IDate = number | string | Date ; type DateFormats = { [ p ] : string ; } ; interface TimeLocale { weekdays : string [ ] ; formats : DateFormats ; } const parseDate = ( date ) => { if ( date instanceof Date ) { return date ; } return new Date ( date ) ; } ; const getWeeHours = ( ) => new Date ( new Date ( ) . setHours ( 0 , 0 , 0 , 0 ) ) ; const padStart = ( n ) => ( n <= 9 ? '0' : '' ) + n ; const getFormat = ( date ) => { const diff = getWeeHours ( ) . getTime ( ) - date . getTime ( ) ; if ( diff < 0 ) { return 'LT' ; } if ( diff < MS_A_DAY ) { return 'YT' ; } if ( diff < MS_A_WEEK ) { return 'WT' ; } return 'lll' ; } ; function formatDate ( date , locale ) { const $d = parseDate ( date ) ; const format = locale . formats [ getFormat ( $d ) ] ; const dates = { YYYY : `${ $d . getFullYear ( ) }` , M : `${ $d . getMonth ( ) + 1 }` , D : `${ $d . getDate ( ) }` , dddd : locale . weekdays [ $d . getDay ( ) ] , HH : padStart ( $d . getHours ( ) ) , mm : padStart ( $d . getMinutes ( ) ) , } ; return format . replace ( REGEX_FORMAT , ( match ) => dates [ match ] ) ; } export default formatDate ;