time_format.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. const utc = require('dayjs/plugin/utc')
  2. const timezone = require('dayjs/plugin/timezone')
  3. import Taro from '@tarojs/taro'
  4. import dayjs from 'dayjs'
  5. import { kIsIOS } from './tools'
  6. dayjs.extend(utc)
  7. dayjs.extend(timezone)
  8. export class TimeFormatter {
  9. static nowDuration = 30
  10. //获取时区偏移多少分钟
  11. static convertGMTtoOffset(gmtString) {
  12. if (!gmtString || (gmtString.indexOf('+') == -1 && gmtString.indexOf('-') == -1)) {
  13. // console.error('gmtString error', gmtString)
  14. // return 0
  15. gmtString = 'GMT+0800'
  16. }
  17. // 提取符号、小时和分钟
  18. var sign = gmtString.substring(3, 4); // 提取符号 "+" 或 "-"
  19. var hours = parseInt(gmtString.substring(4, 6)); // 提取小时部分
  20. var minutes = parseInt(gmtString.substring(6, 8)); // 提取分钟部分
  21. // 计算偏移量(以分钟为单位)
  22. var offset = (hours * 60 + minutes) * (sign === '+' ? 1 : -1);
  23. return offset;
  24. }
  25. //把本地时间戳更改为指定时区的时间戳
  26. static transferTimestamp(timestamp: number, timeZone: string) {
  27. if (!timeZone || timeZone.length == 0) {
  28. return timestamp
  29. }
  30. var date = new Date(timestamp)
  31. if (timeZone) {
  32. var localOffset = date.getTimezoneOffset()
  33. var targetOffset = localOffset + TimeFormatter.convertGMTtoOffset(timeZone)
  34. // 计算目标时间值(毫秒数加上偏移量的毫秒数)
  35. var targetTime = date.getTime() + (targetOffset * 60 * 1000);
  36. // 创建目标时区的 Date 对象
  37. var targetDate = new Date(targetTime);
  38. return targetDate.getTime()
  39. }
  40. return timestamp
  41. }
  42. static timeZoneOffset(timeZone: string) {
  43. if (!timeZone || timeZone.length == 0) {
  44. return 0
  45. }
  46. var date = new Date()
  47. if (timeZone) {
  48. var localOffset = date.getTimezoneOffset()
  49. return localOffset + TimeFormatter.convertGMTtoOffset(timeZone)
  50. }
  51. return 0
  52. }
  53. //格式化时间
  54. //今天 08:00
  55. //昨天 08:00
  56. //明天 08:00
  57. //YYYY-MM-DD HH:mm
  58. static formatTimestamp(timestamp: number): string {
  59. const currentDate = new Date();
  60. const inputDate = new Date(timestamp);
  61. // 判断是否是今天
  62. if (
  63. inputDate.getDate() === currentDate.getDate() &&
  64. inputDate.getMonth() === currentDate.getMonth() &&
  65. inputDate.getFullYear() === currentDate.getFullYear()
  66. ) {
  67. return `${TimeFormatter.getTodayUnit()} ${TimeFormatter.formatTime(inputDate)}`;
  68. }
  69. // 判断是否是昨天
  70. const yesterday = new Date();
  71. yesterday.setDate(currentDate.getDate() - 1);
  72. if (
  73. inputDate.getDate() === yesterday.getDate() &&
  74. inputDate.getMonth() === yesterday.getMonth() &&
  75. inputDate.getFullYear() === yesterday.getFullYear()
  76. ) {
  77. return `${TimeFormatter.getYesterdayUnit()} ${TimeFormatter.formatTime(inputDate)}`;
  78. }
  79. // 判断是否是明天
  80. const tomorrow = new Date();
  81. tomorrow.setDate(currentDate.getDate() + 1);
  82. if (
  83. inputDate.getDate() === tomorrow.getDate() &&
  84. inputDate.getMonth() === tomorrow.getMonth() &&
  85. inputDate.getFullYear() === tomorrow.getFullYear()
  86. ) {
  87. return `${TimeFormatter.getTomorrowUnit()} ${TimeFormatter.formatTime(inputDate)}`;
  88. }
  89. // 返回 YYYY-MM-DD HH:mm
  90. return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber(
  91. inputDate.getDate()
  92. )} ${TimeFormatter.formatTime(inputDate)}`;
  93. }
  94. static dateTimeFormate(timestamp: number, ignoreWeek?: boolean) {
  95. const currentDate = new Date();
  96. const inputDate = new Date(timestamp);
  97. // 判断是否是今天
  98. if (
  99. inputDate.getDate() === currentDate.getDate() &&
  100. inputDate.getMonth() === currentDate.getMonth() &&
  101. inputDate.getFullYear() === currentDate.getFullYear()
  102. ) {
  103. // if (global.language == 'en') {
  104. // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getTodayUnit()}`
  105. // }
  106. return `${TimeFormatter.getTodayUnit()} ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`;
  107. }
  108. // 判断是否是昨天
  109. const yesterday = new Date();
  110. yesterday.setDate(currentDate.getDate() - 1);
  111. if (
  112. inputDate.getDate() === yesterday.getDate() &&
  113. inputDate.getMonth() === yesterday.getMonth() &&
  114. inputDate.getFullYear() === yesterday.getFullYear()
  115. ) {
  116. // if (global.language == 'en') {
  117. // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getYesterdayUnit()}`;
  118. // }
  119. return `${TimeFormatter.getYesterdayUnit()} ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`;
  120. }
  121. // if (global.language == 'en') {
  122. // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getDateAndWeek(timestamp)}`
  123. // }
  124. if (ignoreWeek) {
  125. return TimeFormatter.getDate(timestamp) + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
  126. }
  127. return TimeFormatter.getDateAndWeek(timestamp) + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
  128. }
  129. static dateTimeFormate2(timestamp: number) {
  130. const inputDate = new Date(timestamp);
  131. var dt
  132. if (global.language == 'en') {
  133. dt = `${TimeFormatter.getMonth(inputDate.getMonth() + 1)} ${inputDate.getDate()}`
  134. }
  135. dt = `${TimeFormatter.getMonth(inputDate.getMonth() + 1)}${inputDate.getDate()}日`
  136. return dt + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
  137. }
  138. //显示完整日期
  139. static timelineFullFormatTime(timestamp: number): string {
  140. var date = new Date(timestamp)
  141. var str = `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`;
  142. if (global.language == 'en') {
  143. return `${TimeFormatter.getDayOfWeek(date.getDay())} ${TimeFormatter.getMonth(date.getMonth() + 1)} ${date.getDate()} ${str}`
  144. }
  145. return `${TimeFormatter.getMonth(date.getMonth() + 1)}${date.getDate()}日 ${TimeFormatter.getDayOfWeek(date.getDay())} ${str}`
  146. }
  147. //只显示时间
  148. static timelineFormatTime(timestamp: number, isTestUser?: boolean): string {
  149. if (!timestamp) {
  150. return ' '
  151. }
  152. var date = new Date(timestamp)
  153. // 返回 HH:mm
  154. var str = `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`;
  155. if (isTestUser) {
  156. str += `:${TimeFormatter.formatNumber(date.getSeconds())}`
  157. }
  158. return str
  159. }
  160. //2.基于日期显示日期,省略今天描述
  161. static dateDescription(timestamp: number, showToday?: boolean, showFullDate?: boolean): string {
  162. if (!timestamp) {
  163. return ''
  164. }
  165. const currentDate = new Date();
  166. const inputDate = new Date(timestamp);
  167. // 判断是否是今天
  168. if (
  169. inputDate.getDate() === currentDate.getDate() &&
  170. inputDate.getMonth() === currentDate.getMonth() &&
  171. inputDate.getFullYear() === currentDate.getFullYear() &&
  172. !showFullDate
  173. ) {
  174. if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000 && currentDate.getTime() - timestamp >= 0) {
  175. return TimeFormatter.getJustNowUnit()
  176. }
  177. return showToday ? TimeFormatter.getTodayUnit() : ``;
  178. }
  179. // 判断是否是昨天
  180. const yesterday = new Date();
  181. yesterday.setDate(currentDate.getDate() - 1);
  182. if (
  183. inputDate.getDate() === yesterday.getDate() &&
  184. inputDate.getMonth() === yesterday.getMonth() &&
  185. inputDate.getFullYear() === yesterday.getFullYear() &&
  186. !showFullDate
  187. ) {
  188. return TimeFormatter.getYesterdayUnit();
  189. }
  190. // 判断是否是明天
  191. const tomorrow = new Date();
  192. tomorrow.setDate(currentDate.getDate() + 1);
  193. if (
  194. inputDate.getDate() === tomorrow.getDate() &&
  195. inputDate.getMonth() === tomorrow.getMonth() &&
  196. inputDate.getFullYear() === tomorrow.getFullYear() &&
  197. !showFullDate
  198. ) {
  199. return TimeFormatter.getTomorrowUnit();
  200. }
  201. // const utcDate1 = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate())
  202. // const utcDate2 = Date.UTC(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate())
  203. // const oneDayMilliseconds = 24 * 60 * 60 * 1000; // 一天的毫秒数
  204. // var dayDifference = Math.floor((utcDate2 - utcDate1) / oneDayMilliseconds);
  205. // if (dayDifference < 0) {
  206. var strMonth = TimeFormatter.getMonth(inputDate.getMonth() + 1)
  207. var strDt = ''
  208. var strYear = ''
  209. if (currentDate.getFullYear() != inputDate.getFullYear()) {
  210. strYear = inputDate.getFullYear() + ''
  211. strDt = strYear + '年'
  212. }
  213. if (global.language == 'en') {
  214. if (strYear.length > 0) {
  215. return strMonth + ' ' + inputDate.getDate() + ',' + strYear
  216. }
  217. return strMonth + ' ' + inputDate.getDate()
  218. }
  219. strDt = strDt + strMonth
  220. strDt = strDt + (inputDate.getDate()) + '日'
  221. return strDt
  222. // }
  223. // return global.language == 'en'?`${dayDifference} days from now`:`${dayDifference}天后`
  224. // return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber(
  225. // inputDate.getDate()
  226. // )}`;
  227. }
  228. //3. datedescription+时间,刚刚时隐藏时间
  229. static datetimeDescription(timestamp: number): string {
  230. const currentDate = new Date();
  231. if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000) {
  232. return TimeFormatter.dateDescription(timestamp, true)
  233. }
  234. if (global.language == 'en') {
  235. return TimeFormatter.dateDescription(timestamp, true) + ' ' + TimeFormatter.timeDescription(timestamp)
  236. }
  237. return TimeFormatter.dateDescription(timestamp, true) + '' + TimeFormatter.timeDescription(timestamp)
  238. }
  239. static timeDescription(timestamp): string {
  240. const date = new Date(timestamp);
  241. return `${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}`;
  242. }
  243. static formatTime(date: Date): string {
  244. return `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}:${TimeFormatter.formatNumber(date.getSeconds())}`;
  245. }
  246. static formatNumber(num: number): string {
  247. return num.toString().padStart(2, '0');
  248. }
  249. static getYearByDate(num: number): string {
  250. if (global.language == 'en') {
  251. return (num + '').substring(0, 4)
  252. }
  253. return (num + '').substring(0, 4) + '年'
  254. }
  255. static getMonthAndDayByDate(num: number): string {
  256. const dt = new Date((num + '').substring(0, 4) + '/' +
  257. (num + '').substring(4, 6) + '/' +
  258. (num + '').substring(6));
  259. const now = new Date();
  260. const diff = now.getTime() - dt.getTime();
  261. const day = 1000 * 60 * 60 * 24;
  262. if (diff < day) {
  263. return TimeFormatter.getTodayUnit();
  264. } else if (diff < 2 * day) {
  265. return TimeFormatter.getYesterdayUnit();
  266. } else {
  267. var month = parseInt((num + '').substring(4, 6))
  268. var date = parseInt((num + '').substring(6, 8))
  269. if (global.language == 'en') {
  270. return TimeFormatter.getMonth(month) + ' ' + date
  271. }
  272. return TimeFormatter.getMonth(month) + date + '日'
  273. }
  274. }
  275. static getMonthAndDayByTimestamp(num: number, showFullDate?: boolean): string {
  276. const dt = new Date(num);
  277. const now = new Date();
  278. const diff = now.getTime() - dt.getTime();
  279. const day = 1000 * 60 * 60 * 24;
  280. if (diff < day && !showFullDate) {
  281. return TimeFormatter.getTodayUnit();
  282. } else if (diff < 2 * day && !showFullDate) {
  283. return TimeFormatter.getYesterdayUnit();
  284. } else {
  285. var month = dt.getMonth() + 1
  286. var date = dt.getDate()
  287. if (global.language == 'en') {
  288. return TimeFormatter.getMonth(month) + ' ' + date
  289. }
  290. return TimeFormatter.getMonth(month) + date + '日'
  291. }
  292. }
  293. static getTimeByTimestamp(num: number): string {
  294. const dt = new Date(num);
  295. var hour = dt.getHours()
  296. var minute = dt.getMinutes()
  297. var formateTime = TimeFormatter.padZero(hour) + ':' + TimeFormatter.padZero(minute)
  298. return formateTime
  299. }
  300. //duration 根据起终点时间,忽略精度,如果两个时间点小于60s,则保留精度,否则为分钟
  301. static durationFormate(startTimestamp: number, endTimestamp: number, showDays?: boolean) {
  302. var start = startTimestamp;
  303. var end = endTimestamp;
  304. const diff = Math.abs(end - start);
  305. if (diff > 60000) {
  306. var startTime = new Date(start)
  307. startTime.setSeconds(0)
  308. startTime.setMilliseconds(0)
  309. var endTime = new Date(end)
  310. endTime.setSeconds(0)
  311. endTime.setMilliseconds(0)
  312. start = startTime.getTime()
  313. end = endTime.getTime()
  314. }
  315. return TimeFormatter.calculateTimeDifference(start, end, showDays)
  316. }
  317. static durationFormate2(startTimestamp: number, endTimestamp: number) {
  318. var start = startTimestamp;
  319. var end = endTimestamp;
  320. const diff = Math.abs(end - start);
  321. if (diff > 60000) {
  322. var startTime = new Date(start)
  323. startTime.setSeconds(0)
  324. startTime.setMilliseconds(0)
  325. var endTime = new Date(end)
  326. endTime.setSeconds(0)
  327. endTime.setMilliseconds(0)
  328. start = startTime.getTime()
  329. end = endTime.getTime()
  330. }
  331. return TimeFormatter.calculateTimeDifference(start, end)
  332. }
  333. //计算时间间隔
  334. static calculateTimeDifference(startTimestamp: number, endTimestamp: number, showDays?: boolean): string {
  335. const diff = Math.abs(endTimestamp - startTimestamp);
  336. // 计算小时、分钟和秒数
  337. let hours = Math.floor(diff / (1000 * 60 * 60));
  338. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  339. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  340. if (showDays) {
  341. const days = Math.floor(hours / 24)
  342. hours = hours % 24
  343. var str = ''
  344. if (days > 0) {
  345. str += `${days}${TimeFormatter.getDaysUnit(days)}`
  346. }
  347. if (hours > 0) {
  348. str += `${hours}${TimeFormatter.getHoursUnit(hours)}`
  349. }
  350. if (minutes > 0) {
  351. str += `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`
  352. }
  353. return str;
  354. }
  355. // 根据间隔的大小返回不同的格式
  356. if (diff < 60000) {
  357. return `${seconds}${TimeFormatter.getSecondsUnit(seconds)}`;
  358. } else if (diff < 3600000) {
  359. return `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  360. } else {
  361. if (minutes == 0) {
  362. return `${hours}${TimeFormatter.getHoursUnit(hours)}`;
  363. }
  364. return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  365. }
  366. }
  367. //格式化时间间隔
  368. static formateTimeDifference(startTimestamp: number, endTimestamp: number, ingoreSeconds?: boolean): string {
  369. const diff = Math.abs(endTimestamp - startTimestamp);
  370. // 计算小时、分钟和秒数
  371. const hours = Math.floor(diff / (1000 * 60 * 60));
  372. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  373. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  374. // 根据间隔的大小返回不同的格式
  375. if (diff < 60000) {
  376. return `00:00:${TimeFormatter.padZero(seconds)}`;
  377. } else if (diff < 3600000) {
  378. return `00:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  379. } else {
  380. if (ingoreSeconds) return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  381. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  382. }
  383. }
  384. static formateTime(timestamp: number) {
  385. const date = new Date(timestamp);
  386. return `${TimeFormatter.padZero(date.getMonth() + 1)}-${TimeFormatter.padZero(date.getDate())} ${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}:${TimeFormatter.padZero(date.getSeconds())}`;
  387. }
  388. static formateHourMinute(startTimestamp: number, endTimestamp: number): string {
  389. const diff = Math.abs(endTimestamp - startTimestamp);
  390. // 计算小时、分钟和秒数
  391. const hours = Math.floor(diff / (1000 * 60 * 60));
  392. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  393. return (hours < 10 ? `0${hours}` : `${hours}`) + ':' + (minutes < 10 ? `0${minutes}` : `${minutes}`);
  394. }
  395. static countdown = (dt: number, end = Date.now(), showDays?: boolean): string => {
  396. // const end = Date.now();
  397. const time = end > dt ? Math.floor((end - dt) / 1000) : Math.ceil((dt - end) / 1000)//Math.ceil((end>dt?end-dt:dt-end)/1000);
  398. let hours = Math.floor(time / 3600);
  399. const minutes = Math.floor((time % 3600) / 60);
  400. const seconds = Math.floor(time % 60);
  401. if (showDays) {
  402. const days = Math.floor(hours / 24)
  403. hours = hours % 24
  404. var str = ''
  405. if (days > 0) {
  406. str += `${days}${TimeFormatter.getDaysUnit(days)}`
  407. }
  408. str += `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  409. return str;
  410. }
  411. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  412. };
  413. //计算正计时
  414. static formateTimeNow = (dt: number, end = Date.now()): string => {
  415. // const end = Date.now();
  416. const time = Math.floor((end > dt ? end - dt : dt - end) / 1000);
  417. const hours = Math.floor(time / 3600);
  418. const minutes = Math.floor((time % 3600) / 60);
  419. const seconds = Math.floor(time % 60);
  420. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  421. };
  422. static workoutTime = (time: number): string => {
  423. const hours = Math.floor(time / 3600);
  424. const minutes = Math.floor((time % 3600) / 60);
  425. const seconds = Math.floor(time % 60);
  426. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  427. }
  428. static padZero = (num: number): string => {
  429. return num.toString().padStart(2, '0');
  430. };
  431. //根据时间段和一个时间,推算另外一个时间
  432. static calculateTimeByTimeRange = (timeRange: number, strTime: string, isStart: boolean): string => {
  433. console.log(timeRange, strTime, isStart)
  434. var list = strTime.split(':');
  435. var time = parseInt(list[0]) * 60 + parseInt(list[1]);
  436. if (isStart) {
  437. time = time + timeRange;
  438. }
  439. else {
  440. time = time - timeRange;
  441. }
  442. time = time < 0 ? time + 24 * 60 : time;
  443. time = time >= 24 * 60 ? time - 24 * 60 : time;
  444. var hour = Math.floor(time / 60);
  445. var minute = time % 60;
  446. return `${TimeFormatter.padZero(hour)}:${TimeFormatter.padZero(minute)}`;
  447. }
  448. static formateDurationBySeconds = (left: number) => {
  449. const hours = Math.floor(left / 3600);
  450. const minutes = Math.floor((left % 3600) / 60);
  451. const seconds = Math.floor(left % 60);
  452. var str = ''
  453. if (hours > 0) {
  454. str = str + hours + TimeFormatter.getHoursUnit(hours)
  455. }
  456. if (minutes > 0) {
  457. str = str + minutes + TimeFormatter.getMinutesUnit(minutes)
  458. }
  459. if (seconds > 0) {
  460. str = str + seconds + TimeFormatter.getSecondsUnit(seconds)
  461. }
  462. return str
  463. }
  464. static workoutTimeAndUnitList = (count: number) => {
  465. const hours = Math.floor(count / 3600);
  466. const minutes = Math.floor((count % 3600) / 60);
  467. const seconds = Math.floor(count % 60);
  468. var values: any = []
  469. var units: any = []
  470. if (hours > 0) {
  471. values.push(hours)
  472. units.push(TimeFormatter.getHoursUnit(hours))
  473. }
  474. if (minutes > 0) {
  475. values.push(minutes)
  476. units.push(TimeFormatter.getMinutesUnit(minutes))
  477. }
  478. if (seconds > 0) {
  479. values.push(seconds)
  480. units.push(TimeFormatter.getSecondsUnit(seconds))
  481. }
  482. return {
  483. values: values,
  484. units: units
  485. }
  486. }
  487. //获取今天的日期和星期几
  488. static getDate = (timestamp: number) => {
  489. const now = new Date();
  490. var dt = new Date(timestamp)
  491. dt.setSeconds(0)
  492. dt.setMilliseconds(0)
  493. dt.setMinutes(0)
  494. dt.setHours(0)
  495. const diff = now.getTime() - dt.getTime();
  496. const day = 1000 * 60 * 60 * 24;
  497. if (diff < day) {
  498. return TimeFormatter.getTodayUnit();
  499. } else if (diff < 2 * day) {
  500. return TimeFormatter.getYesterdayUnit();
  501. } else {
  502. if (global.language == 'en') {
  503. return `${TimeFormatter.getDayOfWeek(dt.getDay())} ${TimeFormatter.getMonth(dt.getMonth() + 1)} ${dt.getDate()}`
  504. }
  505. return `${TimeFormatter.getMonth(dt.getMonth() + 1)}${dt.getDate()}日`
  506. }
  507. }
  508. //获取今天的日期和星期几
  509. static getDateAndWeek = (timestamp: number, ignore = false) => {
  510. const now = new Date();
  511. var dt = new Date(timestamp)
  512. dt.setSeconds(0)
  513. dt.setMilliseconds(0)
  514. dt.setMinutes(0)
  515. dt.setHours(0)
  516. const diff = now.getTime() - dt.getTime();
  517. const day = 1000 * 60 * 60 * 24;
  518. if (diff < day && !ignore) {
  519. return TimeFormatter.getTodayUnit();
  520. } else if (diff < 2 * day && !ignore) {
  521. return TimeFormatter.getYesterdayUnit();
  522. } else {
  523. if (global.language == 'en') {
  524. return `${TimeFormatter.getDayOfWeek(dt.getDay())} ${TimeFormatter.getMonth(dt.getMonth() + 1)} ${dt.getDate()}`
  525. }
  526. return `${TimeFormatter.getMonth(dt.getMonth() + 1)}${dt.getDate()}日 ${TimeFormatter.getDayOfWeek(dt.getDay())}`
  527. }
  528. }
  529. //获取当前时间(hh:mm)
  530. static getCurrentHourAndMinute = () => {
  531. var now = new Date()
  532. // var localOffset = now.getTimezoneOffset()
  533. // console.log(localOffset)
  534. return `${TimeFormatter.padZero(now.getHours())}:${TimeFormatter.padZero(now.getMinutes())}`;
  535. }
  536. //获取时长单位
  537. static getSecondsUnit = (seconds, isFull?: boolean) => {
  538. if (global.language == 'en') {
  539. if (isFull) {
  540. return seconds > 1 ? ' seconds ' : ' second '
  541. }
  542. return seconds > 1 ? ' secs ' : ' sec '
  543. }
  544. return '秒'
  545. }
  546. static getMinutesUnit = (minutes, isFull?: boolean) => {
  547. if (global.language == 'en') {
  548. if (isFull) {
  549. return minutes > 1 ? ' minutes ' : ' minute '
  550. }
  551. return minutes > 1 ? ' mins ' : ' min '
  552. }
  553. return '分钟'
  554. }
  555. static getDaysUnit = (days, isFull?: boolean) => {
  556. if (global.language == 'en') {
  557. if (isFull) {
  558. return days != 1 ? ' days ' : ' day '
  559. }
  560. return days != 1 ? ' d ' : ' d '
  561. }
  562. return '天'
  563. }
  564. static getHoursUnit = (hours, isFull?: boolean) => {
  565. if (global.language == 'en') {
  566. if (isFull) {
  567. return hours != 1 ? ' hours ' : ' hour '
  568. }
  569. return hours != 1 ? ' hrs ' : ' hr '
  570. }
  571. return '小时'
  572. }
  573. static getTodayUnit = () => {
  574. return global.language == 'en' ? 'Today' : '今天'
  575. }
  576. static getYesterdayUnit = () => {
  577. return global.language == 'en' ? 'Yesterday' : '昨天'
  578. }
  579. static getTomorrowUnit = () => {
  580. return global.language == 'en' ? 'Tomorrow' : '明天'
  581. }
  582. static getJustNowUnit = () => {
  583. return global.language == 'en' ? 'Just now' : '刚刚'
  584. }
  585. static getDayOfWeek = (index, isFull?: boolean) => {
  586. var weeks = ['日', '一', '二', '三', '四', '五', '六']
  587. var weeks2 = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
  588. ];
  589. var weeksFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  590. if (global.language == 'en') {
  591. if (isFull) {
  592. return weeksFull[index]
  593. }
  594. return weeks2[index]
  595. }
  596. if (isFull)
  597. return '星期' + weeks[index]
  598. return '周' + weeks[index]
  599. }
  600. static getMonth = (index) => {
  601. const monthNames = [
  602. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  603. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  604. ];
  605. if (global.language == 'en') {
  606. return monthNames[index - 1]
  607. }
  608. return index + '月'
  609. }
  610. //获取本周一零点的时间戳
  611. static getMondayTimestamp = () => {
  612. const now = new Date();
  613. const currentDay = now.getDay(); // Get the current day of the week (0 for Sunday, 1 for Monday, etc.)
  614. const startOfWeek = new Date(now); // Create a new Date object with the current date and time
  615. // Calculate the difference in milliseconds to the beginning of the week
  616. const diffToMonday = (currentDay - 1) * 24 * 60 * 60 * 1000; // Subtract 1 day worth of milliseconds for each day after Monday
  617. startOfWeek.setTime(now.getTime() - diffToMonday); // Set the time to the beginning of the week (Monday at 00:00:00)
  618. startOfWeek.setHours(0)
  619. startOfWeek.setMinutes(0)
  620. startOfWeek.setSeconds(0)
  621. startOfWeek.setMilliseconds(0)
  622. const timestamp = startOfWeek.getTime(); // Get the timestamp in milliseconds
  623. return timestamp
  624. }
  625. static getSundayTimestamp = () => {
  626. const now = new Date();
  627. const currentDay = now.getDay(); // Get the current day of the week (0 for Sunday, 1 for Monday, etc.)
  628. const startOfWeek = new Date(now); // Create a new Date object with the current date and time
  629. // Calculate the difference in milliseconds to the beginning of the week
  630. const diffToMonday = currentDay * 24 * 60 * 60 * 1000; // Subtract 1 day worth of milliseconds for each day after Monday
  631. startOfWeek.setTime(now.getTime() - diffToMonday); // Set the time to the beginning of the week (Monday at 00:00:00)
  632. startOfWeek.setHours(0)
  633. startOfWeek.setMinutes(0)
  634. startOfWeek.setSeconds(0)
  635. startOfWeek.setMilliseconds(0)
  636. const timestamp = startOfWeek.getTime(); // Get the timestamp in milliseconds
  637. return timestamp
  638. }
  639. //hh:mm转换成秒数
  640. static timestringToSeconds = (strTime: string) => {
  641. var list = strTime.split(':')
  642. return parseInt(list[0]) * 3600 + parseInt(list[1]) * 60
  643. }
  644. static tzTimeFormateLocalTime = (timestamp: number, timeZone: string, formate: string) => {
  645. if (!timeZone || timeZone.length == 0) {
  646. return dayjs(timestamp).format(formate)
  647. }
  648. if (process.env.TARO_ENV == 'weapp') {
  649. return dayjs(timestamp).tz(timeZone).format(formate)
  650. }
  651. else {
  652. if (kIsIOS) {
  653. return dayjs(timestamp).tz(timeZone).format(formate)
  654. }
  655. var moment = require('moment-timezone');
  656. return moment(timestamp).tz(timeZone).format(formate)
  657. }
  658. }
  659. static dayjsFormat = (timestamp: number, showToday = false) => {
  660. const today = dayjs();
  661. const dt = dayjs(timestamp);
  662. var strTime = dt.format('HH:mm ')
  663. const yesterday = today.subtract(1, 'day');
  664. const tomorrow = today.subtract(-1, 'day');
  665. if (dt.isSame(today, 'day')) {
  666. if (showToday) {
  667. if (global.language == 'en') return 'Today ' + strTime;
  668. return '今天 ' + strTime
  669. }
  670. return strTime;
  671. } else if (dt.isSame(yesterday, 'day')) {
  672. if (global.language == 'en') return 'Yesterday ' + strTime;
  673. return '昨天 ' + strTime;
  674. } else if (dt.isSame(tomorrow, 'day')) {
  675. if (global.language == 'en') return 'Tomorrow ' + strTime;
  676. return '明天 ' + strTime;
  677. } else {
  678. if (global.language == 'en') return dt.format('MMM DD ') + strTime;
  679. return dt.format('MMMDD日 ') + strTime;
  680. }
  681. }
  682. static tzNameToGMT = (timeZone: string) => {
  683. var minutes = 0
  684. if (!timeZone || timeZone.length == 0) {
  685. minutes = dayjs().utcOffset()
  686. }
  687. if (process.env.TARO_ENV == 'weapp' || kIsIOS) {
  688. minutes = dayjs().tz(timeZone).utcOffset()
  689. }
  690. else {
  691. var moment = require('moment-timezone');
  692. minutes = moment().tz(timeZone).utcOffset()
  693. }
  694. const offsetHours = Math.abs(Math.floor(minutes / 60));
  695. const offsetMinutesRemaining = Math.abs(minutes % 60);
  696. // 构建 GMT 格式的字符串
  697. let gmt = 'GMT';
  698. if (minutes < 0) {
  699. gmt += '+';
  700. } else {
  701. gmt += '-';
  702. }
  703. gmt += `${offsetHours.toString().padStart(2, '0')}:${offsetMinutesRemaining.toString().padStart(2, '0')}`;
  704. return gmt;
  705. }
  706. static tzLocalTime = (timestamp: number, timeZone: string) => {
  707. if (!timeZone || timeZone.length == 0) {
  708. return dayjs(timestamp)
  709. }
  710. if (process.env.TARO_ENV == 'weapp') {
  711. return dayjs(timestamp).tz(timeZone)
  712. }
  713. else {
  714. var moment = require('moment-timezone');
  715. return moment(timestamp).tz(timeZone)
  716. }
  717. }
  718. static isToday = (timestamp: number) => {
  719. if (dayjs().format('YYYY-MM-DD') == dayjs(timestamp).format('YYYY-MM-DD')) {
  720. return true
  721. }
  722. return false
  723. }
  724. static isYesterday = (timestamp: number) => {
  725. if (dayjs().format('YYYY-MM-DD') == dayjs(timestamp + 24 * 3600 * 1000).format('YYYY-MM-DD')) {
  726. return true
  727. }
  728. return false
  729. }
  730. static dayTagText = (begin: number, end: number) => {
  731. const date1 = dayjs(begin);
  732. const date2 = dayjs(end);
  733. // 获取日期部分(去掉时间)
  734. const startDate = date1.startOf('day');
  735. const endDate = date2.startOf('day');
  736. const days = endDate.diff(startDate, 'day')
  737. if (days > 0)
  738. return '+' + days;
  739. return ''
  740. }
  741. }