export class TimeFormatter { static nowDuration = 30 static convertGMTtoOffset(gmtString) { // 提取符号、小时和分钟 var sign = gmtString.substring(3, 4); // 提取符号 "+" 或 "-" var hours = parseInt(gmtString.substring(4, 6)); // 提取小时部分 var minutes = parseInt(gmtString.substring(6, 8)); // 提取分钟部分 // 计算偏移量(以分钟为单位) var offset = (hours * 60 + minutes) * (sign === '+' ? 1 : -1); return offset; } //把本地时间戳更改为指定时区的时间戳 static transferTimestamp(timestamp: number, timeZone: string) { if (!timeZone || timeZone.length == 0) { return timestamp } var date = new Date(timestamp) if (timeZone) { var localOffset = date.getTimezoneOffset() var targetOffset = localOffset + TimeFormatter.convertGMTtoOffset(timeZone) // 计算目标时间值(毫秒数加上偏移量的毫秒数) var targetTime = date.getTime() + (targetOffset * 60 * 1000); // 创建目标时区的 Date 对象 var targetDate = new Date(targetTime); return targetDate.getTime() } return timestamp } //格式化时间 static formatTimestamp(timestamp: number): string { const currentDate = new Date(); const inputDate = new Date(timestamp); // 判断是否是今天 if ( inputDate.getDate() === currentDate.getDate() && inputDate.getMonth() === currentDate.getMonth() && inputDate.getFullYear() === currentDate.getFullYear() ) { return `${TimeFormatter.getTodayUnit()} ${TimeFormatter.formatTime(inputDate)}`; } // 判断是否是昨天 const yesterday = new Date(); yesterday.setDate(currentDate.getDate() - 1); if ( inputDate.getDate() === yesterday.getDate() && inputDate.getMonth() === yesterday.getMonth() && inputDate.getFullYear() === yesterday.getFullYear() ) { return `${TimeFormatter.getYesterdayUnit()} ${TimeFormatter.formatTime(inputDate)}`; } // 判断是否是明天 const tomorrow = new Date(); tomorrow.setDate(currentDate.getDate() + 1); if ( inputDate.getDate() === tomorrow.getDate() && inputDate.getMonth() === tomorrow.getMonth() && inputDate.getFullYear() === tomorrow.getFullYear() ) { return `${TimeFormatter.getTomorrowUnit()} ${TimeFormatter.formatTime(inputDate)}`; } // 返回 YYYY-MM-DD HH:mm return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber( inputDate.getDate() )} ${TimeFormatter.formatTime(inputDate)}`; } static dateTimeFormate(timestamp: number) { const currentDate = new Date(); const inputDate = new Date(timestamp); // 判断是否是今天 if ( inputDate.getDate() === currentDate.getDate() && inputDate.getMonth() === currentDate.getMonth() && inputDate.getFullYear() === currentDate.getFullYear() ) { // if (global.language == 'en') { // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getTodayUnit()}` // } return `${TimeFormatter.getTodayUnit()} ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`; } // 判断是否是昨天 const yesterday = new Date(); yesterday.setDate(currentDate.getDate() - 1); if ( inputDate.getDate() === yesterday.getDate() && inputDate.getMonth() === yesterday.getMonth() && inputDate.getFullYear() === yesterday.getFullYear() ) { // if (global.language == 'en') { // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getYesterdayUnit()}`; // } return `${TimeFormatter.getYesterdayUnit()} ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`; } // if (global.language == 'en') { // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getDateAndWeek(timestamp)}` // } return TimeFormatter.getDateAndWeek(timestamp) + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}` } //显示完整日期 static timelineFullFormatTime(timestamp: number): string { var date = new Date(timestamp) var str = `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`; if (global.language == 'en') { return `${TimeFormatter.getDayOfWeek(date.getDay())} ${TimeFormatter.getMonth(date.getMonth() + 1)} ${date.getDate()} ${str}` } return `${TimeFormatter.getMonth(date.getMonth() + 1)}${date.getDate()}日 ${TimeFormatter.getDayOfWeek(date.getDay())} ${str}` } //只显示时间 static timelineFormatTime(timestamp: number, isTestUser?: boolean): string { if (!timestamp) { return ' ' } var date = new Date(timestamp) // 返回 HH:mm var str = `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`; if (isTestUser) { str += `:${TimeFormatter.formatNumber(date.getSeconds())}` } return str } //2.基于日期显示日期,省略今天描述 static dateDescription(timestamp: number, showToday?: boolean, showFullDate?: boolean): string { if (!timestamp) { return '' } const currentDate = new Date(); const inputDate = new Date(timestamp); // 判断是否是今天 if ( inputDate.getDate() === currentDate.getDate() && inputDate.getMonth() === currentDate.getMonth() && inputDate.getFullYear() === currentDate.getFullYear() && !showFullDate ) { if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000 && currentDate.getTime() - timestamp >= 0) { return TimeFormatter.getJustNowUnit() } return showToday ? TimeFormatter.getTodayUnit() : ``; } // 判断是否是昨天 const yesterday = new Date(); yesterday.setDate(currentDate.getDate() - 1); if ( inputDate.getDate() === yesterday.getDate() && inputDate.getMonth() === yesterday.getMonth() && inputDate.getFullYear() === yesterday.getFullYear() && !showFullDate ) { return TimeFormatter.getYesterdayUnit(); } // 判断是否是明天 const tomorrow = new Date(); tomorrow.setDate(currentDate.getDate() + 1); if ( inputDate.getDate() === tomorrow.getDate() && inputDate.getMonth() === tomorrow.getMonth() && inputDate.getFullYear() === tomorrow.getFullYear() && !showFullDate ) { return TimeFormatter.getTomorrowUnit(); } const utcDate1 = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) const utcDate2 = Date.UTC(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate()) const oneDayMilliseconds = 24 * 60 * 60 * 1000; // 一天的毫秒数 var dayDifference = Math.floor((utcDate2 - utcDate1) / oneDayMilliseconds); if (dayDifference < 0) { var strMonth = TimeFormatter.getMonth(inputDate.getMonth() + 1) var strDt = '' var strYear = '' if (currentDate.getFullYear() != inputDate.getFullYear()) { strYear = inputDate.getFullYear() + '' strDt = strYear + '年' } if (global.language == 'en') { if (strYear.length > 0) { return strMonth + ' ' + inputDate.getDate() + ',' + strYear } return strMonth + ' ' + inputDate.getDate() } strDt = strDt + strMonth strDt = strDt + (inputDate.getDate()) + '日' return strDt } return `${dayDifference}天后` // return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber( // inputDate.getDate() // )}`; } //3. datedescription+时间,刚刚时隐藏时间 static datetimeDescription(timestamp: number): string { const currentDate = new Date(); if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000) { return TimeFormatter.dateDescription(timestamp, true) } if (global.language == 'en') { return TimeFormatter.dateDescription(timestamp, true) + ' ' + TimeFormatter.timeDescription(timestamp) } return TimeFormatter.dateDescription(timestamp, true) + '' + TimeFormatter.timeDescription(timestamp) } static timeDescription(timestamp): string { const date = new Date(timestamp); return `${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}`; } static formatTime(date: Date): string { return `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}:${TimeFormatter.formatNumber(date.getSeconds())}`; } static formatNumber(num: number): string { return num.toString().padStart(2, '0'); } static getYearByDate(num: number): string { if (global.language == 'en') { return (num + '').substring(0, 4) } return (num + '').substring(0, 4) + '年' } static getMonthAndDayByDate(num: number): string { const dt = new Date((num + '').substring(0, 4) + '/' + (num + '').substring(4, 6) + '/' + (num + '').substring(6)); const now = new Date(); const diff = now.getTime() - dt.getTime(); const day = 1000 * 60 * 60 * 24; if (diff < day) { return TimeFormatter.getTodayUnit(); } else if (diff < 2 * day) { return TimeFormatter.getYesterdayUnit(); } else { var month = parseInt((num + '').substring(4, 6)) var date = parseInt((num + '').substring(6, 8)) if (global.language == 'en') { return TimeFormatter.getMonth(month) + ' ' + date } return TimeFormatter.getMonth(month) + date + '日' } } static getMonthAndDayByTimestamp(num: number, showFullDate?: boolean): string { const dt = new Date(num); const now = new Date(); const diff = now.getTime() - dt.getTime(); const day = 1000 * 60 * 60 * 24; if (diff < day && !showFullDate) { return TimeFormatter.getTodayUnit(); } else if (diff < 2 * day && !showFullDate) { return TimeFormatter.getYesterdayUnit(); } else { var month = dt.getMonth() + 1 var date = dt.getDate() if (global.language == 'en') { return TimeFormatter.getMonth(month) + ' ' + date } return TimeFormatter.getMonth(month) + date + '日' } } static getTimeByTimestamp(num: number): string { const dt = new Date(num); var hour = dt.getHours() var minute = dt.getMinutes() var formateTime = TimeFormatter.padZero(hour) + ':' + TimeFormatter.padZero(minute) return formateTime } //duration 根据起终点时间,忽略精度,如果两个时间点小于60s,则保留精度,否则为分钟 static durationFormate(startTimestamp: number, endTimestamp: number) { var start = startTimestamp; var end = endTimestamp; const diff = Math.abs(end - start); if (diff > 60000) { var startTime = new Date(start) startTime.setSeconds(0) startTime.setMilliseconds(0) var endTime = new Date(end) endTime.setSeconds(0) endTime.setMilliseconds(0) start = startTime.getTime() end = endTime.getTime() } return TimeFormatter.calculateTimeDifference(start, end) } static durationFormate2(startTimestamp: number, endTimestamp: number) { var start = startTimestamp; var end = endTimestamp; const diff = Math.abs(end - start); if (diff > 60000) { var startTime = new Date(start) startTime.setSeconds(0) startTime.setMilliseconds(0) var endTime = new Date(end) endTime.setSeconds(0) endTime.setMilliseconds(0) start = startTime.getTime() end = endTime.getTime() } return TimeFormatter.calculateTimeDifference(start, end) } //计算时间间隔 static calculateTimeDifference(startTimestamp: number, endTimestamp: number, ingoreSeconds?: boolean): string { const diff = Math.abs(endTimestamp - startTimestamp); // 计算小时、分钟和秒数 const hours = Math.floor(diff / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((diff % (1000 * 60)) / 1000); // 根据间隔的大小返回不同的格式 if (diff < 60000) { return `${seconds}${TimeFormatter.getSecondsUnit(seconds)}`; } else if (diff < 3600000) { return `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`; } else { if (minutes == 0) { return `${hours}${TimeFormatter.getHoursUnit(hours)}`; } return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`; } } //格式化时间间隔 static formateTimeDifference(startTimestamp: number, endTimestamp: number, ingoreSeconds?: boolean): string { const diff = Math.abs(endTimestamp - startTimestamp); // 计算小时、分钟和秒数 const hours = Math.floor(diff / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((diff % (1000 * 60)) / 1000); // 根据间隔的大小返回不同的格式 if (diff < 60000) { return `00:00:${TimeFormatter.padZero(seconds)}`; } else if (diff < 3600000) { return `00:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`; } else { if (ingoreSeconds) return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`; return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`; } } static formateTime(timestamp: number) { const date = new Date(timestamp); return `${TimeFormatter.padZero(date.getMonth() + 1)}-${TimeFormatter.padZero(date.getDate())} ${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}:${TimeFormatter.padZero(date.getSeconds())}`; } static formateHourMinute(startTimestamp: number, endTimestamp: number): string { const diff = Math.abs(endTimestamp - startTimestamp); // 计算小时、分钟和秒数 const hours = Math.floor(diff / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); return (hours < 10 ? `0${hours}` : `${hours}`) + ':' + (minutes < 10 ? `0${minutes}` : `${minutes}`); } static countdown = (dt: number, end = Date.now()): string => { // const end = Date.now(); const time = end > dt ? Math.floor((end - dt) / 1000) : Math.ceil((dt - end) / 1000)//Math.ceil((end>dt?end-dt:dt-end)/1000); const hours = Math.floor(time / 3600); const minutes = Math.floor((time % 3600) / 60); const seconds = Math.floor(time % 60); return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`; }; //计算正计时 static formateTimeNow = (dt: number, end = Date.now()): string => { // const end = Date.now(); const time = Math.floor((end > dt ? end - dt : dt - end) / 1000); const hours = Math.floor(time / 3600); const minutes = Math.floor((time % 3600) / 60); const seconds = Math.floor(time % 60); return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`; }; static workoutTime = (time: number): string => { const hours = Math.floor(time / 3600); const minutes = Math.floor((time % 3600) / 60); const seconds = Math.floor(time % 60); return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`; } static padZero = (num: number): string => { return num.toString().padStart(2, '0'); }; //根据时间段和一个时间,推算另外一个时间 static calculateTimeByTimeRange = (timeRange: number, strTime: string, isStart: boolean): string => { console.log(timeRange, strTime, isStart) var list = strTime.split(':'); var time = parseInt(list[0]) * 60 + parseInt(list[1]); if (isStart) { time = time + timeRange; } else { time = time - timeRange; } time = time < 0 ? time + 24 * 60 : time; time = time >= 24 * 60 ? time - 24 * 60 : time; var hour = Math.floor(time / 60); var minute = time % 60; return `${TimeFormatter.padZero(hour)}:${TimeFormatter.padZero(minute)}`; } static formateDurationBySeconds = (left: number) => { const hours = Math.floor(left / 3600); const minutes = Math.floor((left % 3600) / 60); const seconds = Math.floor(left % 60); var str = '' if (hours > 0) { str = str + hours + TimeFormatter.getHoursUnit(hours) } if (minutes > 0) { str = str + minutes + TimeFormatter.getMinutesUnit(minutes) } if (seconds > 0) { str = str + seconds + TimeFormatter.getSecondsUnit(seconds) } return str } static workoutTimeAndUnitList = (count: number) => { const hours = Math.floor(count / 3600); const minutes = Math.floor((count % 3600) / 60); const seconds = Math.floor(count % 60); var values: any = [] var units: any = [] if (hours > 0) { values.push(hours) units.push(TimeFormatter.getHoursUnit(hours)) } if (minutes > 0) { values.push(minutes) units.push(TimeFormatter.getMinutesUnit(minutes)) } if (seconds > 0) { values.push(seconds) units.push(TimeFormatter.getSecondsUnit(seconds)) } return { values: values, units: units } } //获取今天的日期和星期几 static getDateAndWeek = (timestamp: number, ignore = false) => { const now = new Date(); var dt = new Date(timestamp) dt.setSeconds(0) dt.setMilliseconds(0) dt.setMinutes(0) dt.setHours(0) const diff = now.getTime() - dt.getTime(); const day = 1000 * 60 * 60 * 24; if (diff < day && !ignore) { return TimeFormatter.getTodayUnit(); } else if (diff < 2 * day && !ignore) { return TimeFormatter.getYesterdayUnit(); } else { if (global.language == 'en') { return `${TimeFormatter.getDayOfWeek(dt.getDay())} ${TimeFormatter.getMonth(dt.getMonth() + 1)} ${dt.getDate()}` } return `${TimeFormatter.getMonth(dt.getMonth() + 1)}${dt.getDate()}日 ${TimeFormatter.getDayOfWeek(dt.getDay())}` } } //获取当前时间(hh:mm) static getCurrentHourAndMinute = () => { var now = new Date() // var localOffset = now.getTimezoneOffset() // console.log(localOffset) // debugger return `${TimeFormatter.padZero(now.getHours())}:${TimeFormatter.padZero(now.getMinutes())}`; } //获取时长单位 static getSecondsUnit = (seconds, isFull?: boolean) => { if (global.language == 'en') { if (isFull) { return seconds > 1 ? ' seconds ' : ' second ' } return seconds > 1 ? ' secs ' : ' sec ' } return '秒' } static getMinutesUnit = (minutes, isFull?: boolean) => { if (global.language == 'en') { if (isFull) { return minutes > 1 ? ' minutes ' : ' minute ' } return minutes > 1 ? ' mins ' : ' min ' } return '分钟' } static getHoursUnit = (hours, isFull?: boolean) => { if (global.language == 'en') { if (isFull) { return hours > 1 ? ' hours ' : ' hour ' } return hours > 1 ? ' hrs ' : ' hr ' } return '小时' } static getTodayUnit = () => { return global.language == 'en' ? 'Today' : '今天' } static getYesterdayUnit = () => { return global.language == 'en' ? 'Yesterday' : '昨天' } static getTomorrowUnit = () => { return global.language == 'en' ? 'Tomorrow' : '明天' } static getJustNowUnit = () => { return global.language == 'en' ? 'Just now' : '刚刚' } static getDayOfWeek = (index, isFull?: boolean) => { var weeks = ['日', '一', '二', '三', '四', '五', '六'] var weeks2 = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]; var weeksFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] if (global.language == 'en') { if (isFull) { return weeksFull[index] } return weeks2[index] } return '星期' + weeks[index] } static getMonth = (index) => { const monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; if (global.language == 'en') { return monthNames[index - 1] } return index + '月' } //获取本周一零点的时间戳 static getMondayTimestamp = () => { const now = new Date(); const currentDay = now.getDay(); // Get the current day of the week (0 for Sunday, 1 for Monday, etc.) const startOfWeek = new Date(now); // Create a new Date object with the current date and time // Calculate the difference in milliseconds to the beginning of the week const diffToMonday = (currentDay - 1) * 24 * 60 * 60 * 1000; // Subtract 1 day worth of milliseconds for each day after Monday startOfWeek.setTime(now.getTime() - diffToMonday); // Set the time to the beginning of the week (Monday at 00:00:00) startOfWeek.setHours(0) startOfWeek.setMinutes(0) startOfWeek.setSeconds(0) startOfWeek.setMilliseconds(0) const timestamp = startOfWeek.getTime(); // Get the timestamp in milliseconds return timestamp } //hh:mm转换成秒数 static timestringToSeconds = (strTime: string) => { var list = strTime.split(':') return parseInt(list[0]) * 3600 + parseInt(list[1]) * 60 } }