| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872 |
- const utc = require('dayjs/plugin/utc')
- const timezone = require('dayjs/plugin/timezone')
- import Taro from '@tarojs/taro'
- import dayjs from 'dayjs'
- import { kIsIOS } from './tools'
- dayjs.extend(utc)
- dayjs.extend(timezone)
- export class TimeFormatter {
- static nowDuration = 30
- //获取时区偏移多少分钟
- static convertGMTtoOffset(gmtString) {
- if (!gmtString || (gmtString.indexOf('+') == -1 && gmtString.indexOf('-') == -1)) {
- // console.error('gmtString error', gmtString)
- // return 0
- gmtString = 'GMT+0800'
- }
- // 提取符号、小时和分钟
- 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 timeZoneOffset(timeZone: string) {
- if (!timeZone || timeZone.length == 0) {
- return 0
- }
- var date = new Date()
- if (timeZone) {
- var localOffset = date.getTimezoneOffset()
- return localOffset + TimeFormatter.convertGMTtoOffset(timeZone)
- }
- return 0
- }
- //格式化时间
- //今天 08:00
- //昨天 08:00
- //明天 08:00
- //YYYY-MM-DD HH:mm
- 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, ignoreWeek?: boolean) {
- 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)}`
- // }
- if (ignoreWeek) {
- return TimeFormatter.getDate(timestamp) + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
- }
- return TimeFormatter.getDateAndWeek(timestamp) + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
- }
- static dateTimeFormate2(timestamp: number) {
- const inputDate = new Date(timestamp);
- var dt
- if (global.language == 'en') {
- dt = `${TimeFormatter.getMonth(inputDate.getMonth() + 1)} ${inputDate.getDate()}`
- }
- dt = `${TimeFormatter.getMonth(inputDate.getMonth() + 1)}${inputDate.getDate()}日`
- return dt + ' ' + `${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 global.language == 'en'?`${dayDifference} days from now`:`${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, showDays?: boolean) {
- 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, showDays)
- }
- 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, showDays?: boolean,ignoreSeconds?:boolean): string {
- if (ignoreSeconds){
- var date1 = new Date(startTimestamp)
- var date2 = new Date(endTimestamp)
- date1.setSeconds(0,0)
- date2.setSeconds(0,0)
- startTimestamp = date1.getTime()
- endTimestamp = date2.getTime()
- }
-
- const diff = Math.abs(endTimestamp - startTimestamp);
- // 计算小时、分钟和秒数
- let 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 (showDays) {
- const days = Math.floor(hours / 24)
- hours = hours % 24
- var str = ''
- if (days > 0) {
- str += `${days}${TimeFormatter.getDaysUnit(days)}`
- }
- if (hours > 0) {
- str += `${hours}${TimeFormatter.getHoursUnit(hours)}`
- }
- if (minutes > 0) {
- str += `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`
- }
- return str;
- }
- // 根据间隔的大小返回不同的格式
- 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(), showDays?: boolean): 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);
- let hours = Math.floor(time / 3600);
- const minutes = Math.floor((time % 3600) / 60);
- const seconds = Math.floor(time % 60);
- if (showDays) {
- const days = Math.floor(hours / 24)
- hours = hours % 24
- var str = ''
- if (days > 0) {
- str += `${days}${TimeFormatter.getDaysUnit(days)}`
- }
- str += `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
- return str;
- }
- 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 getDate = (timestamp: number) => {
- 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) {
- return TimeFormatter.getTodayUnit();
- } else if (diff < 2 * day) {
- 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()}日`
- }
- }
- //获取今天的日期和星期几
- 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)
- 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 getDaysUnit = (days, isFull?: boolean) => {
- if (global.language == 'en') {
- if (isFull) {
- return days != 1 ? ' days ' : ' day '
- }
- return days != 1 ? ' d ' : ' d '
- }
- 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]
- }
- if (isFull)
- return '星期' + weeks[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
- }
- static getSundayTimestamp = () => {
- 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 * 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
- }
- static tzTimeFormateLocalTime = (timestamp: number, timeZone: string, formate: string) => {
- if (!timeZone || timeZone.length == 0) {
- return dayjs(timestamp).format(formate)
- }
- if (process.env.TARO_ENV == 'weapp') {
- return dayjs(timestamp).tz(timeZone).format(formate)
- }
- else {
- if (kIsIOS) {
- return dayjs(timestamp).tz(timeZone).format(formate)
- }
- var moment = require('moment-timezone');
- return moment(timestamp).tz(timeZone).format(formate)
- }
- }
- static dayjsFormat = (timestamp: number, showToday = false) => {
- const today = dayjs();
- const dt = dayjs(timestamp);
- var strTime = dt.format('HH:mm ')
- const yesterday = today.subtract(1, 'day');
- const tomorrow = today.subtract(-1, 'day');
- if (dt.isSame(today, 'day')) {
- if (showToday) {
- if (global.language == 'en') return 'Today ' + strTime;
- return '今天 ' + strTime
- }
- return strTime;
- } else if (dt.isSame(yesterday, 'day')) {
- if (global.language == 'en') return 'Yesterday ' + strTime;
- return '昨天 ' + strTime;
- } else if (dt.isSame(tomorrow, 'day')) {
- if (global.language == 'en') return 'Tomorrow ' + strTime;
- return '明天 ' + strTime;
- } else {
- if (global.language == 'en') return dt.format('MMM DD ') + strTime;
- return dt.format('MMMDD日 ') + strTime;
- }
- }
- static tzNameToGMT = (timeZone: string) => {
- var minutes = 0
- if (!timeZone || timeZone.length == 0) {
- minutes = dayjs().utcOffset()
- }
- if (process.env.TARO_ENV == 'weapp' || kIsIOS) {
- minutes = dayjs().tz(timeZone).utcOffset()
- }
- else {
- var moment = require('moment-timezone');
- minutes = moment().tz(timeZone).utcOffset()
- }
- const offsetHours = Math.abs(Math.floor(minutes / 60));
- const offsetMinutesRemaining = Math.abs(minutes % 60);
- // 构建 GMT 格式的字符串
- let gmt = 'GMT';
- if (minutes < 0) {
- gmt += '+';
- } else {
- gmt += '-';
- }
- gmt += `${offsetHours.toString().padStart(2, '0')}:${offsetMinutesRemaining.toString().padStart(2, '0')}`;
- return gmt;
- }
- static tzLocalTime = (timestamp: number, timeZone: string) => {
- if (!timeZone || timeZone.length == 0) {
- return dayjs(timestamp)
- }
- if (process.env.TARO_ENV == 'weapp') {
- return dayjs(timestamp).tz(timeZone)
- }
- else {
- var moment = require('moment-timezone');
- return moment(timestamp).tz(timeZone)
- }
- }
- static isToday = (timestamp: number) => {
- if (dayjs().format('YYYY-MM-DD') == dayjs(timestamp).format('YYYY-MM-DD')) {
- return true
- }
- return false
- }
- static isYesterday = (timestamp: number) => {
- if (dayjs().format('YYYY-MM-DD') == dayjs(timestamp + 24 * 3600 * 1000).format('YYYY-MM-DD')) {
- return true
- }
- return false
- }
- static dayTagText = (begin: number, end: number) => {
- const date1 = dayjs(begin);
- const date2 = dayjs(end);
- // 获取日期部分(去掉时间)
- const startDate = date1.startOf('day');
- const endDate = date2.startOf('day');
- const days = endDate.diff(startDate, 'day')
- if (days > 0)
- return '+' + days+(global.language=='en'?'d':'天');
- return ''
- }
- }
|