time_format.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. debugger
  98. // 判断是否是今天
  99. if (
  100. inputDate.getDate() === currentDate.getDate() &&
  101. inputDate.getMonth() === currentDate.getMonth() &&
  102. inputDate.getFullYear() === currentDate.getFullYear()
  103. ) {
  104. // if (global.language == 'en') {
  105. // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getTodayUnit()}`
  106. // }
  107. return `${TimeFormatter.getTodayUnit()} ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`;
  108. }
  109. // 判断是否是昨天
  110. const yesterday = new Date();
  111. yesterday.setDate(currentDate.getDate() - 1);
  112. if (
  113. inputDate.getDate() === yesterday.getDate() &&
  114. inputDate.getMonth() === yesterday.getMonth() &&
  115. inputDate.getFullYear() === yesterday.getFullYear()
  116. ) {
  117. // if (global.language == 'en') {
  118. // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getYesterdayUnit()}`;
  119. // }
  120. return `${TimeFormatter.getYesterdayUnit()} ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`;
  121. }
  122. // if (global.language == 'en') {
  123. // return `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())} ${TimeFormatter.getDateAndWeek(timestamp)}`
  124. // }
  125. if (ignoreWeek) {
  126. return TimeFormatter.getDate(timestamp) + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
  127. }
  128. return TimeFormatter.getDateAndWeek(timestamp) + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
  129. }
  130. static dateTimeFormate2(timestamp: number) {
  131. const inputDate = new Date(timestamp);
  132. var dt
  133. if (global.language == 'en') {
  134. dt = `${TimeFormatter.getMonth(inputDate.getMonth() + 1)} ${inputDate.getDate()}`
  135. }
  136. dt = `${TimeFormatter.getMonth(inputDate.getMonth() + 1)}${inputDate.getDate()}日`
  137. return dt + ' ' + `${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
  138. }
  139. //显示完整日期
  140. static timelineFullFormatTime(timestamp: number): string {
  141. var date = new Date(timestamp)
  142. var str = `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`;
  143. if (global.language == 'en') {
  144. return `${TimeFormatter.getDayOfWeek(date.getDay())} ${TimeFormatter.getMonth(date.getMonth() + 1)} ${date.getDate()} ${str}`
  145. }
  146. return `${TimeFormatter.getMonth(date.getMonth() + 1)}${date.getDate()}日 ${TimeFormatter.getDayOfWeek(date.getDay())} ${str}`
  147. }
  148. //只显示时间
  149. static timelineFormatTime(timestamp: number, isTestUser?: boolean): string {
  150. if (!timestamp) {
  151. return ' '
  152. }
  153. var date = new Date(timestamp)
  154. // 返回 HH:mm
  155. var str = `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`;
  156. if (isTestUser) {
  157. str += `:${TimeFormatter.formatNumber(date.getSeconds())}`
  158. }
  159. return str
  160. }
  161. //2.基于日期显示日期,省略今天描述
  162. static dateDescription(timestamp: number, showToday?: boolean, showFullDate?: boolean): string {
  163. if (!timestamp) {
  164. return ''
  165. }
  166. const currentDate = new Date();
  167. const inputDate = new Date(timestamp);
  168. // 判断是否是今天
  169. if (
  170. inputDate.getDate() === currentDate.getDate() &&
  171. inputDate.getMonth() === currentDate.getMonth() &&
  172. inputDate.getFullYear() === currentDate.getFullYear() &&
  173. !showFullDate
  174. ) {
  175. if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000 && currentDate.getTime() - timestamp >= 0) {
  176. return TimeFormatter.getJustNowUnit()
  177. }
  178. return showToday ? TimeFormatter.getTodayUnit() : ``;
  179. }
  180. // 判断是否是昨天
  181. const yesterday = new Date();
  182. yesterday.setDate(currentDate.getDate() - 1);
  183. if (
  184. inputDate.getDate() === yesterday.getDate() &&
  185. inputDate.getMonth() === yesterday.getMonth() &&
  186. inputDate.getFullYear() === yesterday.getFullYear() &&
  187. !showFullDate
  188. ) {
  189. return TimeFormatter.getYesterdayUnit();
  190. }
  191. // 判断是否是明天
  192. const tomorrow = new Date();
  193. tomorrow.setDate(currentDate.getDate() + 1);
  194. if (
  195. inputDate.getDate() === tomorrow.getDate() &&
  196. inputDate.getMonth() === tomorrow.getMonth() &&
  197. inputDate.getFullYear() === tomorrow.getFullYear() &&
  198. !showFullDate
  199. ) {
  200. return TimeFormatter.getTomorrowUnit();
  201. }
  202. // const utcDate1 = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate())
  203. // const utcDate2 = Date.UTC(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate())
  204. // const oneDayMilliseconds = 24 * 60 * 60 * 1000; // 一天的毫秒数
  205. // var dayDifference = Math.floor((utcDate2 - utcDate1) / oneDayMilliseconds);
  206. // if (dayDifference < 0) {
  207. var strMonth = TimeFormatter.getMonth(inputDate.getMonth() + 1)
  208. var strDt = ''
  209. var strYear = ''
  210. if (currentDate.getFullYear() != inputDate.getFullYear()) {
  211. strYear = inputDate.getFullYear() + ''
  212. strDt = strYear + '年'
  213. }
  214. if (global.language == 'en') {
  215. if (strYear.length > 0) {
  216. return strMonth + ' ' + inputDate.getDate() + ',' + strYear
  217. }
  218. return strMonth + ' ' + inputDate.getDate()
  219. }
  220. strDt = strDt + strMonth
  221. strDt = strDt + (inputDate.getDate()) + '日'
  222. return strDt
  223. // }
  224. // return global.language == 'en'?`${dayDifference} days from now`:`${dayDifference}天后`
  225. // return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber(
  226. // inputDate.getDate()
  227. // )}`;
  228. }
  229. //3. datedescription+时间,刚刚时隐藏时间
  230. static datetimeDescription(timestamp: number): string {
  231. const currentDate = new Date();
  232. if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000) {
  233. return TimeFormatter.dateDescription(timestamp, true)
  234. }
  235. if (global.language == 'en') {
  236. return TimeFormatter.dateDescription(timestamp, true) + ' ' + TimeFormatter.timeDescription(timestamp)
  237. }
  238. return TimeFormatter.dateDescription(timestamp, true) + '' + TimeFormatter.timeDescription(timestamp)
  239. }
  240. static timeDescription(timestamp): string {
  241. const date = new Date(timestamp);
  242. return `${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}`;
  243. }
  244. static formatTime(date: Date): string {
  245. return `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}:${TimeFormatter.formatNumber(date.getSeconds())}`;
  246. }
  247. static formatNumber(num: number): string {
  248. return num.toString().padStart(2, '0');
  249. }
  250. static getYearByDate(num: number): string {
  251. if (global.language == 'en') {
  252. return (num + '').substring(0, 4)
  253. }
  254. return (num + '').substring(0, 4) + '年'
  255. }
  256. static getMonthAndDayByDate(num: number): string {
  257. const dt = new Date((num + '').substring(0, 4) + '/' +
  258. (num + '').substring(4, 6) + '/' +
  259. (num + '').substring(6));
  260. const now = new Date();
  261. const diff = now.getTime() - dt.getTime();
  262. const day = 1000 * 60 * 60 * 24;
  263. if (diff < day) {
  264. return TimeFormatter.getTodayUnit();
  265. } else if (diff < 2 * day) {
  266. return TimeFormatter.getYesterdayUnit();
  267. } else {
  268. var month = parseInt((num + '').substring(4, 6))
  269. var date = parseInt((num + '').substring(6, 8))
  270. if (global.language == 'en') {
  271. return TimeFormatter.getMonth(month) + ' ' + date
  272. }
  273. return TimeFormatter.getMonth(month) + date + '日'
  274. }
  275. }
  276. static getMonthAndDayByTimestamp(num: number, showFullDate?: boolean): string {
  277. const dt = new Date(num);
  278. const now = new Date();
  279. const diff = now.getTime() - dt.getTime();
  280. const day = 1000 * 60 * 60 * 24;
  281. if (diff < day && !showFullDate) {
  282. return TimeFormatter.getTodayUnit();
  283. } else if (diff < 2 * day && !showFullDate) {
  284. return TimeFormatter.getYesterdayUnit();
  285. } else {
  286. var month = dt.getMonth() + 1
  287. var date = dt.getDate()
  288. if (global.language == 'en') {
  289. return TimeFormatter.getMonth(month) + ' ' + date
  290. }
  291. return TimeFormatter.getMonth(month) + date + '日'
  292. }
  293. }
  294. static getTimeByTimestamp(num: number): string {
  295. const dt = new Date(num);
  296. var hour = dt.getHours()
  297. var minute = dt.getMinutes()
  298. var formateTime = TimeFormatter.padZero(hour) + ':' + TimeFormatter.padZero(minute)
  299. return formateTime
  300. }
  301. //duration 根据起终点时间,忽略精度,如果两个时间点小于60s,则保留精度,否则为分钟
  302. static durationFormate(startTimestamp: number, endTimestamp: number, showDays?: boolean) {
  303. var start = startTimestamp;
  304. var end = endTimestamp;
  305. const diff = Math.abs(end - start);
  306. if (diff > 60000) {
  307. var startTime = new Date(start)
  308. startTime.setSeconds(0)
  309. startTime.setMilliseconds(0)
  310. var endTime = new Date(end)
  311. endTime.setSeconds(0)
  312. endTime.setMilliseconds(0)
  313. start = startTime.getTime()
  314. end = endTime.getTime()
  315. }
  316. return TimeFormatter.calculateTimeDifference(start, end, showDays)
  317. }
  318. static durationFormate2(startTimestamp: number, endTimestamp: number) {
  319. var start = startTimestamp;
  320. var end = endTimestamp;
  321. const diff = Math.abs(end - start);
  322. if (diff > 60000) {
  323. var startTime = new Date(start)
  324. startTime.setSeconds(0)
  325. startTime.setMilliseconds(0)
  326. var endTime = new Date(end)
  327. endTime.setSeconds(0)
  328. endTime.setMilliseconds(0)
  329. start = startTime.getTime()
  330. end = endTime.getTime()
  331. }
  332. return TimeFormatter.calculateTimeDifference(start, end)
  333. }
  334. //计算时间间隔
  335. static calculateTimeDifference(startTimestamp: number, endTimestamp: number, showDays?: boolean): string {
  336. const diff = Math.abs(endTimestamp - startTimestamp);
  337. // 计算小时、分钟和秒数
  338. let hours = Math.floor(diff / (1000 * 60 * 60));
  339. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  340. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  341. if (showDays) {
  342. const days = Math.floor(hours / 24)
  343. hours = hours % 24
  344. var str = ''
  345. if (days > 0) {
  346. str += `${days}${TimeFormatter.getDaysUnit(days)}`
  347. }
  348. if (hours > 0) {
  349. str += `${hours}${TimeFormatter.getHoursUnit(hours)}`
  350. }
  351. if (minutes > 0) {
  352. str += `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`
  353. }
  354. return str;
  355. }
  356. // 根据间隔的大小返回不同的格式
  357. if (diff < 60000) {
  358. return `${seconds}${TimeFormatter.getSecondsUnit(seconds)}`;
  359. } else if (diff < 3600000) {
  360. return `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  361. } else {
  362. if (minutes == 0) {
  363. return `${hours}${TimeFormatter.getHoursUnit(hours)}`;
  364. }
  365. return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  366. }
  367. }
  368. //格式化时间间隔
  369. static formateTimeDifference(startTimestamp: number, endTimestamp: number, ingoreSeconds?: boolean): string {
  370. const diff = Math.abs(endTimestamp - startTimestamp);
  371. // 计算小时、分钟和秒数
  372. const hours = Math.floor(diff / (1000 * 60 * 60));
  373. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  374. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  375. // 根据间隔的大小返回不同的格式
  376. if (diff < 60000) {
  377. return `00:00:${TimeFormatter.padZero(seconds)}`;
  378. } else if (diff < 3600000) {
  379. return `00:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  380. } else {
  381. if (ingoreSeconds) return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  382. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  383. }
  384. }
  385. static formateTime(timestamp: number) {
  386. const date = new Date(timestamp);
  387. return `${TimeFormatter.padZero(date.getMonth() + 1)}-${TimeFormatter.padZero(date.getDate())} ${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}:${TimeFormatter.padZero(date.getSeconds())}`;
  388. }
  389. static formateHourMinute(startTimestamp: number, endTimestamp: number): string {
  390. const diff = Math.abs(endTimestamp - startTimestamp);
  391. // 计算小时、分钟和秒数
  392. const hours = Math.floor(diff / (1000 * 60 * 60));
  393. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  394. return (hours < 10 ? `0${hours}` : `${hours}`) + ':' + (minutes < 10 ? `0${minutes}` : `${minutes}`);
  395. }
  396. static countdown = (dt: number, end = Date.now(), showDays?: boolean): string => {
  397. // const end = Date.now();
  398. const time = end > dt ? Math.floor((end - dt) / 1000) : Math.ceil((dt - end) / 1000)//Math.ceil((end>dt?end-dt:dt-end)/1000);
  399. let hours = Math.floor(time / 3600);
  400. const minutes = Math.floor((time % 3600) / 60);
  401. const seconds = Math.floor(time % 60);
  402. if (showDays) {
  403. const days = Math.floor(hours / 24)
  404. hours = hours % 24
  405. var str = ''
  406. if (days > 0) {
  407. str += `${days}${TimeFormatter.getDaysUnit(days)}`
  408. }
  409. str += `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  410. return str;
  411. }
  412. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  413. };
  414. //计算正计时
  415. static formateTimeNow = (dt: number, end = Date.now()): string => {
  416. // const end = Date.now();
  417. const time = Math.floor((end > dt ? end - dt : dt - end) / 1000);
  418. const hours = Math.floor(time / 3600);
  419. const minutes = Math.floor((time % 3600) / 60);
  420. const seconds = Math.floor(time % 60);
  421. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  422. };
  423. static workoutTime = (time: number): string => {
  424. const hours = Math.floor(time / 3600);
  425. const minutes = Math.floor((time % 3600) / 60);
  426. const seconds = Math.floor(time % 60);
  427. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  428. }
  429. static padZero = (num: number): string => {
  430. return num.toString().padStart(2, '0');
  431. };
  432. //根据时间段和一个时间,推算另外一个时间
  433. static calculateTimeByTimeRange = (timeRange: number, strTime: string, isStart: boolean): string => {
  434. console.log(timeRange, strTime, isStart)
  435. var list = strTime.split(':');
  436. var time = parseInt(list[0]) * 60 + parseInt(list[1]);
  437. if (isStart) {
  438. time = time + timeRange;
  439. }
  440. else {
  441. time = time - timeRange;
  442. }
  443. time = time < 0 ? time + 24 * 60 : time;
  444. time = time >= 24 * 60 ? time - 24 * 60 : time;
  445. var hour = Math.floor(time / 60);
  446. var minute = time % 60;
  447. return `${TimeFormatter.padZero(hour)}:${TimeFormatter.padZero(minute)}`;
  448. }
  449. static formateDurationBySeconds = (left: number) => {
  450. const hours = Math.floor(left / 3600);
  451. const minutes = Math.floor((left % 3600) / 60);
  452. const seconds = Math.floor(left % 60);
  453. var str = ''
  454. if (hours > 0) {
  455. str = str + hours + TimeFormatter.getHoursUnit(hours)
  456. }
  457. if (minutes > 0) {
  458. str = str + minutes + TimeFormatter.getMinutesUnit(minutes)
  459. }
  460. if (seconds > 0) {
  461. str = str + seconds + TimeFormatter.getSecondsUnit(seconds)
  462. }
  463. return str
  464. }
  465. static workoutTimeAndUnitList = (count: number) => {
  466. const hours = Math.floor(count / 3600);
  467. const minutes = Math.floor((count % 3600) / 60);
  468. const seconds = Math.floor(count % 60);
  469. var values: any = []
  470. var units: any = []
  471. if (hours > 0) {
  472. values.push(hours)
  473. units.push(TimeFormatter.getHoursUnit(hours))
  474. }
  475. if (minutes > 0) {
  476. values.push(minutes)
  477. units.push(TimeFormatter.getMinutesUnit(minutes))
  478. }
  479. if (seconds > 0) {
  480. values.push(seconds)
  481. units.push(TimeFormatter.getSecondsUnit(seconds))
  482. }
  483. return {
  484. values: values,
  485. units: units
  486. }
  487. }
  488. //获取今天的日期和星期几
  489. static getDate = (timestamp: number) => {
  490. const now = new Date();
  491. var dt = new Date(timestamp)
  492. dt.setSeconds(0)
  493. dt.setMilliseconds(0)
  494. dt.setMinutes(0)
  495. dt.setHours(0)
  496. const diff = now.getTime() - dt.getTime();
  497. const day = 1000 * 60 * 60 * 24;
  498. if (diff < day) {
  499. return TimeFormatter.getTodayUnit();
  500. } else if (diff < 2 * day) {
  501. return TimeFormatter.getYesterdayUnit();
  502. } else {
  503. if (global.language == 'en') {
  504. return `${TimeFormatter.getDayOfWeek(dt.getDay())} ${TimeFormatter.getMonth(dt.getMonth() + 1)} ${dt.getDate()}`
  505. }
  506. return `${TimeFormatter.getMonth(dt.getMonth() + 1)}${dt.getDate()}日`
  507. }
  508. }
  509. //获取今天的日期和星期几
  510. static getDateAndWeek = (timestamp: number, ignore = false) => {
  511. const now = new Date();
  512. var dt = new Date(timestamp)
  513. dt.setSeconds(0)
  514. dt.setMilliseconds(0)
  515. dt.setMinutes(0)
  516. dt.setHours(0)
  517. const diff = now.getTime() - dt.getTime();
  518. const day = 1000 * 60 * 60 * 24;
  519. if (diff < day && !ignore) {
  520. return TimeFormatter.getTodayUnit();
  521. } else if (diff < 2 * day && !ignore) {
  522. return TimeFormatter.getYesterdayUnit();
  523. } else {
  524. if (global.language == 'en') {
  525. return `${TimeFormatter.getDayOfWeek(dt.getDay())} ${TimeFormatter.getMonth(dt.getMonth() + 1)} ${dt.getDate()}`
  526. }
  527. return `${TimeFormatter.getMonth(dt.getMonth() + 1)}${dt.getDate()}日 ${TimeFormatter.getDayOfWeek(dt.getDay())}`
  528. }
  529. }
  530. //获取当前时间(hh:mm)
  531. static getCurrentHourAndMinute = () => {
  532. var now = new Date()
  533. // var localOffset = now.getTimezoneOffset()
  534. // console.log(localOffset)
  535. return `${TimeFormatter.padZero(now.getHours())}:${TimeFormatter.padZero(now.getMinutes())}`;
  536. }
  537. //获取时长单位
  538. static getSecondsUnit = (seconds, isFull?: boolean) => {
  539. if (global.language == 'en') {
  540. if (isFull) {
  541. return seconds > 1 ? ' seconds ' : ' second '
  542. }
  543. return seconds > 1 ? ' secs ' : ' sec '
  544. }
  545. return '秒'
  546. }
  547. static getMinutesUnit = (minutes, isFull?: boolean) => {
  548. if (global.language == 'en') {
  549. if (isFull) {
  550. return minutes > 1 ? ' minutes ' : ' minute '
  551. }
  552. return minutes > 1 ? ' mins ' : ' min '
  553. }
  554. return '分钟'
  555. }
  556. static getDaysUnit = (days, isFull?: boolean) => {
  557. if (global.language == 'en') {
  558. if (isFull) {
  559. return days > 1 ? ' days ' : ' day '
  560. }
  561. return days > 1 ? ' d ' : ' d '
  562. }
  563. return '天'
  564. }
  565. static getHoursUnit = (hours, isFull?: boolean) => {
  566. if (global.language == 'en') {
  567. if (isFull) {
  568. return hours > 1 ? ' hours ' : ' hour '
  569. }
  570. return hours > 1 ? ' hrs ' : ' hr '
  571. }
  572. return '小时'
  573. }
  574. static getTodayUnit = () => {
  575. return global.language == 'en' ? 'Today' : '今天'
  576. }
  577. static getYesterdayUnit = () => {
  578. return global.language == 'en' ? 'Yesterday' : '昨天'
  579. }
  580. static getTomorrowUnit = () => {
  581. return global.language == 'en' ? 'Tomorrow' : '明天'
  582. }
  583. static getJustNowUnit = () => {
  584. return global.language == 'en' ? 'Just now' : '刚刚'
  585. }
  586. static getDayOfWeek = (index, isFull?: boolean) => {
  587. var weeks = ['日', '一', '二', '三', '四', '五', '六']
  588. var weeks2 = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
  589. ];
  590. var weeksFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  591. if (global.language == 'en') {
  592. if (isFull) {
  593. return weeksFull[index]
  594. }
  595. return weeks2[index]
  596. }
  597. if (isFull)
  598. return '星期' + weeks[index]
  599. return '周' + weeks[index]
  600. }
  601. static getMonth = (index) => {
  602. const monthNames = [
  603. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  604. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  605. ];
  606. if (global.language == 'en') {
  607. return monthNames[index - 1]
  608. }
  609. return index + '月'
  610. }
  611. //获取本周一零点的时间戳
  612. static getMondayTimestamp = () => {
  613. const now = new Date();
  614. const currentDay = now.getDay(); // Get the current day of the week (0 for Sunday, 1 for Monday, etc.)
  615. const startOfWeek = new Date(now); // Create a new Date object with the current date and time
  616. // Calculate the difference in milliseconds to the beginning of the week
  617. const diffToMonday = (currentDay - 1) * 24 * 60 * 60 * 1000; // Subtract 1 day worth of milliseconds for each day after Monday
  618. startOfWeek.setTime(now.getTime() - diffToMonday); // Set the time to the beginning of the week (Monday at 00:00:00)
  619. startOfWeek.setHours(0)
  620. startOfWeek.setMinutes(0)
  621. startOfWeek.setSeconds(0)
  622. startOfWeek.setMilliseconds(0)
  623. const timestamp = startOfWeek.getTime(); // Get the timestamp in milliseconds
  624. return timestamp
  625. }
  626. //hh:mm转换成秒数
  627. static timestringToSeconds = (strTime: string) => {
  628. var list = strTime.split(':')
  629. return parseInt(list[0]) * 3600 + parseInt(list[1]) * 60
  630. }
  631. static tzTimeFormateLocalTime = (timestamp: number, timeZone: string, formate: string) => {
  632. if (!timeZone || timeZone.length == 0) {
  633. return dayjs(timestamp).format(formate)
  634. }
  635. if (process.env.TARO_ENV == 'weapp') {
  636. return dayjs(timestamp).tz(timeZone).format(formate)
  637. }
  638. else {
  639. if (kIsIOS) {
  640. return dayjs(timestamp).tz(timeZone).format(formate)
  641. }
  642. var moment = require('moment-timezone');
  643. return moment(timestamp).tz(timeZone).format(formate)
  644. }
  645. }
  646. static tzLocalTime = (timestamp: number, timeZone: string) => {
  647. if (!timeZone || timeZone.length == 0) {
  648. return dayjs(timestamp)
  649. }
  650. if (process.env.TARO_ENV == 'weapp') {
  651. return dayjs(timestamp).tz(timeZone)
  652. }
  653. else {
  654. var moment = require('moment-timezone');
  655. return moment(timestamp).tz(timeZone)
  656. }
  657. }
  658. }