基於momentjs封裝常用時間工具函式
阿新 • • 發佈:2021-10-21
/* eslint-disable @tuya-fe/i18n-detection */ import moment from 'moment' const defaultFormat = 'YYYY-MM-DD' // 獲取時間格式: 毫秒 export const formatDate = ( date?: moment.MomentInput | string, format = defaultFormat, defaultValue = '-', ): string => { if (date) { return moment(date).format(format) }return defaultValue } export const getMoment = (date) => moment(date) // 獲取當日0點時間 export const getStartTime = (date: any) => { return new Date(new Date(date).toLocaleDateString()).getTime() } // 獲取當日23點59分時間 export const getEndTime = (date: any) => { const dayDate = 24 * 60 * 60 * 1000 - 1 returnnew Date(new Date(new Date(date).toLocaleDateString()).getTime() + dayDate).getTime() } /** * 毫秒轉化為天小時分鐘秒 * @param msParams 毫秒值 * @return string */ export const formatTimeMsToString = (msParams: number | string) => { const ms = +msParams const ss = 1000 const mi = ss * 60 const hh = mi * 60 const dd= hh * 24 const day = parseInt(`${ms / dd}`) const hour = parseInt(`${(ms - day * dd) / hh}`) const minute = parseInt(`${(ms - day * dd - hour * hh) / mi}`) const second = parseInt(`${(ms - day * dd - hour * hh - minute * mi) / ss}`) if (!day && !hour && !minute && !!second) { return '<1分鐘' } let str = '' if (day > 0) { str = `${str}${day}天` } if (hour > 0) { str = `${str}${hour}小時` } if (minute > 0) { str = `${str}${minute}分鐘` } // if (second > 0) { // str = `${str}${second}秒` // } return str } // 相對時間 export const toDuration = function (val) { const cTime = new Date().getTime() // 當前時間 const tTime = val // 目標時間 const diffTime = cTime - tTime //秒-分-時-日-月-年 //console.info(diffTime); if (diffTime < 1000) { return '剛剛' } else if (diffTime <= 60000) { // (60 * 1000) return Math.round(diffTime / 1000) + '秒前' } else if (diffTime <= 3600000) { // (60 * 60 * 1000) return Math.round(diffTime / 60000) + '分鐘前' // (60 * 1000) } else if (diffTime <= 86400000) { // (24* 60 * 60 * 1000) return Math.round(diffTime / 3600000) + '時前' // (60 * 60 * 1000) } else if (diffTime <= 2592000000) { // (30 * 24 * 60 * 60 * 1000) return Math.round(diffTime / 86400000) + '天前' // (24 * 60 * 60 * 1000) } else if (diffTime <= 31104000000) { // (12 * 30 * 24 * 60 * 60 * 1000) return Math.round(diffTime / 2592000000) + '月前' // (30 * 24 * 60 * 60 * 1000) } else { return Math.round(diffTime / 31104000000) + '年前' // (12 * 30 * 24 * 60 * 60 * 1000) } } export const HoursTip = function () { const date = new Date() let hoursTip = '' if (date.getHours() >= 0 && date.getHours() < 12) { hoursTip = '上午好' } else if (date.getHours() >= 12 && date.getHours() < 18) { hoursTip = '下午好' } else { hoursTip = '晚上好' } return hoursTip }