time_format.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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,ignoreSeconds?:boolean): string {
  335. if (ignoreSeconds){
  336. var date1 = new Date(startTimestamp)
  337. var date2 = new Date(endTimestamp)
  338. date1.setSeconds(0,0)
  339. date2.setSeconds(0,0)
  340. startTimestamp = date1.getTime()
  341. endTimestamp = date2.getTime()
  342. }
  343. const diff = Math.abs(endTimestamp - startTimestamp);
  344. // 计算小时、分钟和秒数
  345. let hours = Math.floor(diff / (1000 * 60 * 60));
  346. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  347. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  348. if (showDays) {
  349. const days = Math.floor(hours / 24)
  350. hours = hours % 24
  351. var str = ''
  352. if (days > 0) {
  353. str += `${days}${TimeFormatter.getDaysUnit(days)}`
  354. }
  355. if (hours > 0) {
  356. str += `${hours}${TimeFormatter.getHoursUnit(hours)}`
  357. }
  358. if (minutes > 0) {
  359. str += `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`
  360. }
  361. return str;
  362. }
  363. // 根据间隔的大小返回不同的格式
  364. if (diff < 60000) {
  365. return `${seconds}${TimeFormatter.getSecondsUnit(seconds)}`;
  366. } else if (diff < 3600000) {
  367. return `${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  368. } else {
  369. if (minutes == 0) {
  370. return `${hours}${TimeFormatter.getHoursUnit(hours)}`;
  371. }
  372. return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  373. }
  374. }
  375. //格式化时间间隔
  376. static formateTimeDifference(startTimestamp: number, endTimestamp: number, ingoreSeconds?: boolean): string {
  377. const diff = Math.abs(endTimestamp - startTimestamp);
  378. // 计算小时、分钟和秒数
  379. const hours = Math.floor(diff / (1000 * 60 * 60));
  380. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  381. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  382. // 根据间隔的大小返回不同的格式
  383. if (diff < 60000) {
  384. return `00:00:${TimeFormatter.padZero(seconds)}`;
  385. } else if (diff < 3600000) {
  386. return `00:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  387. } else {
  388. if (ingoreSeconds) return `${hours}${TimeFormatter.getHoursUnit(hours)}${minutes}${TimeFormatter.getMinutesUnit(minutes)}`;
  389. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  390. }
  391. }
  392. static formateTime(timestamp: number) {
  393. const date = new Date(timestamp);
  394. return `${TimeFormatter.padZero(date.getMonth() + 1)}-${TimeFormatter.padZero(date.getDate())} ${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}:${TimeFormatter.padZero(date.getSeconds())}`;
  395. }
  396. static formateHourMinute(startTimestamp: number, endTimestamp: number): string {
  397. const diff = Math.abs(endTimestamp - startTimestamp);
  398. // 计算小时、分钟和秒数
  399. const hours = Math.floor(diff / (1000 * 60 * 60));
  400. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  401. return (hours < 10 ? `0${hours}` : `${hours}`) + ':' + (minutes < 10 ? `0${minutes}` : `${minutes}`);
  402. }
  403. static countdown = (dt: number, end = Date.now(), showDays?: boolean): string => {
  404. // const end = Date.now();
  405. const time = end > dt ? Math.floor((end - dt) / 1000) : Math.ceil((dt - end) / 1000)//Math.ceil((end>dt?end-dt:dt-end)/1000);
  406. let hours = Math.floor(time / 3600);
  407. const minutes = Math.floor((time % 3600) / 60);
  408. const seconds = Math.floor(time % 60);
  409. if (showDays) {
  410. const days = Math.floor(hours / 24)
  411. hours = hours % 24
  412. var str = ''
  413. if (days > 0) {
  414. str += `${days}${TimeFormatter.getDaysUnit(days)}`
  415. }
  416. str += `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  417. return str;
  418. }
  419. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  420. };
  421. //计算正计时
  422. static formateTimeNow = (dt: number, end = Date.now()): string => {
  423. // const end = Date.now();
  424. const time = Math.floor((end > dt ? end - dt : dt - end) / 1000);
  425. const hours = Math.floor(time / 3600);
  426. const minutes = Math.floor((time % 3600) / 60);
  427. const seconds = Math.floor(time % 60);
  428. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  429. };
  430. static workoutTime = (time: number): string => {
  431. const hours = Math.floor(time / 3600);
  432. const minutes = Math.floor((time % 3600) / 60);
  433. const seconds = Math.floor(time % 60);
  434. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  435. }
  436. static padZero = (num: number): string => {
  437. return num.toString().padStart(2, '0');
  438. };
  439. //根据时间段和一个时间,推算另外一个时间
  440. static calculateTimeByTimeRange = (timeRange: number, strTime: string, isStart: boolean): string => {
  441. console.log(timeRange, strTime, isStart)
  442. var list = strTime.split(':');
  443. var time = parseInt(list[0]) * 60 + parseInt(list[1]);
  444. if (isStart) {
  445. time = time + timeRange;
  446. }
  447. else {
  448. time = time - timeRange;
  449. }
  450. time = time < 0 ? time + 24 * 60 : time;
  451. time = time >= 24 * 60 ? time - 24 * 60 : time;
  452. var hour = Math.floor(time / 60);
  453. var minute = time % 60;
  454. return `${TimeFormatter.padZero(hour)}:${TimeFormatter.padZero(minute)}`;
  455. }
  456. static formateDurationBySeconds = (left: number) => {
  457. const hours = Math.floor(left / 3600);
  458. const minutes = Math.floor((left % 3600) / 60);
  459. const seconds = Math.floor(left % 60);
  460. var str = ''
  461. if (hours > 0) {
  462. str = str + hours + TimeFormatter.getHoursUnit(hours)
  463. }
  464. if (minutes > 0) {
  465. str = str + minutes + TimeFormatter.getMinutesUnit(minutes)
  466. }
  467. if (seconds > 0) {
  468. str = str + seconds + TimeFormatter.getSecondsUnit(seconds)
  469. }
  470. return str
  471. }
  472. static workoutTimeAndUnitList = (count: number) => {
  473. const hours = Math.floor(count / 3600);
  474. const minutes = Math.floor((count % 3600) / 60);
  475. const seconds = Math.floor(count % 60);
  476. var values: any = []
  477. var units: any = []
  478. if (hours > 0) {
  479. values.push(hours)
  480. units.push(TimeFormatter.getHoursUnit(hours))
  481. }
  482. if (minutes > 0) {
  483. values.push(minutes)
  484. units.push(TimeFormatter.getMinutesUnit(minutes))
  485. }
  486. if (seconds > 0) {
  487. values.push(seconds)
  488. units.push(TimeFormatter.getSecondsUnit(seconds))
  489. }
  490. return {
  491. values: values,
  492. units: units
  493. }
  494. }
  495. //获取今天的日期和星期几
  496. static getDate = (timestamp: number) => {
  497. const now = new Date();
  498. var dt = new Date(timestamp)
  499. dt.setSeconds(0)
  500. dt.setMilliseconds(0)
  501. dt.setMinutes(0)
  502. dt.setHours(0)
  503. const diff = now.getTime() - dt.getTime();
  504. const day = 1000 * 60 * 60 * 24;
  505. if (diff < day) {
  506. return TimeFormatter.getTodayUnit();
  507. } else if (diff < 2 * day) {
  508. return TimeFormatter.getYesterdayUnit();
  509. } else {
  510. if (global.language == 'en') {
  511. return `${TimeFormatter.getDayOfWeek(dt.getDay())} ${TimeFormatter.getMonth(dt.getMonth() + 1)} ${dt.getDate()}`
  512. }
  513. return `${TimeFormatter.getMonth(dt.getMonth() + 1)}${dt.getDate()}日`
  514. }
  515. }
  516. //获取今天的日期和星期几
  517. static getDateAndWeek = (timestamp: number, ignore = false) => {
  518. const now = new Date();
  519. var dt = new Date(timestamp)
  520. dt.setSeconds(0)
  521. dt.setMilliseconds(0)
  522. dt.setMinutes(0)
  523. dt.setHours(0)
  524. const diff = now.getTime() - dt.getTime();
  525. const day = 1000 * 60 * 60 * 24;
  526. if (diff < day && !ignore) {
  527. return TimeFormatter.getTodayUnit();
  528. } else if (diff < 2 * day && !ignore) {
  529. return TimeFormatter.getYesterdayUnit();
  530. } else {
  531. if (global.language == 'en') {
  532. return `${TimeFormatter.getDayOfWeek(dt.getDay())} ${TimeFormatter.getMonth(dt.getMonth() + 1)} ${dt.getDate()}`
  533. }
  534. return `${TimeFormatter.getMonth(dt.getMonth() + 1)}${dt.getDate()}日 ${TimeFormatter.getDayOfWeek(dt.getDay())}`
  535. }
  536. }
  537. //获取当前时间(hh:mm)
  538. static getCurrentHourAndMinute = () => {
  539. var now = new Date()
  540. // var localOffset = now.getTimezoneOffset()
  541. // console.log(localOffset)
  542. return `${TimeFormatter.padZero(now.getHours())}:${TimeFormatter.padZero(now.getMinutes())}`;
  543. }
  544. //获取时长单位
  545. static getSecondsUnit = (seconds, isFull?: boolean) => {
  546. if (global.language == 'en') {
  547. if (isFull) {
  548. return seconds != 1 ? ' seconds ' : ' second '
  549. }
  550. return seconds != 1 ? ' secs ' : ' sec '
  551. }
  552. return '秒'
  553. }
  554. static getMinutesUnit = (minutes, isFull?: boolean) => {
  555. if (global.language == 'en') {
  556. if (isFull) {
  557. return minutes != 1 ? ' minutes ' : ' minute '
  558. }
  559. return minutes != 1 ? ' mins ' : ' min '
  560. }
  561. return '分钟'
  562. }
  563. static getDaysUnit = (days, isFull?: boolean) => {
  564. if (global.language == 'en') {
  565. if (isFull) {
  566. return days != 1 ? ' days ' : ' day '
  567. }
  568. return days != 1 ? ' d ' : ' d '
  569. }
  570. return '天'
  571. }
  572. static getHoursUnit = (hours, isFull?: boolean) => {
  573. if (global.language == 'en') {
  574. if (isFull) {
  575. return hours != 1 ? ' hours ' : ' hour '
  576. }
  577. return hours != 1 ? ' hrs ' : ' hr '
  578. }
  579. return '小时'
  580. }
  581. static getTodayUnit = () => {
  582. return global.language == 'en' ? 'Today' : '今天'
  583. }
  584. static getYesterdayUnit = () => {
  585. return global.language == 'en' ? 'Yesterday' : '昨天'
  586. }
  587. static getTomorrowUnit = () => {
  588. return global.language == 'en' ? 'Tomorrow' : '明天'
  589. }
  590. static getJustNowUnit = () => {
  591. return global.language == 'en' ? 'Just now' : '刚刚'
  592. }
  593. static getDayOfWeek = (index, isFull?: boolean) => {
  594. var weeks = ['日', '一', '二', '三', '四', '五', '六']
  595. var weeks2 = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
  596. ];
  597. var weeksFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  598. if (global.language == 'en') {
  599. if (isFull) {
  600. return weeksFull[index]
  601. }
  602. return weeks2[index]
  603. }
  604. if (isFull)
  605. return '星期' + weeks[index]
  606. return '周' + weeks[index]
  607. }
  608. static getMonth = (index) => {
  609. const monthNames = [
  610. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  611. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  612. ];
  613. if (global.language == 'en') {
  614. return monthNames[index - 1]
  615. }
  616. return index + '月'
  617. }
  618. //获取本周一零点的时间戳
  619. static getMondayTimestamp = () => {
  620. const now = new Date();
  621. const currentDay = now.getDay(); // Get the current day of the week (0 for Sunday, 1 for Monday, etc.)
  622. const startOfWeek = new Date(now); // Create a new Date object with the current date and time
  623. // Calculate the difference in milliseconds to the beginning of the week
  624. const diffToMonday = (currentDay - 1) * 24 * 60 * 60 * 1000; // Subtract 1 day worth of milliseconds for each day after Monday
  625. startOfWeek.setTime(now.getTime() - diffToMonday); // Set the time to the beginning of the week (Monday at 00:00:00)
  626. startOfWeek.setHours(0)
  627. startOfWeek.setMinutes(0)
  628. startOfWeek.setSeconds(0)
  629. startOfWeek.setMilliseconds(0)
  630. const timestamp = startOfWeek.getTime(); // Get the timestamp in milliseconds
  631. return timestamp
  632. }
  633. static getSundayTimestamp = () => {
  634. const now = new Date();
  635. const currentDay = now.getDay(); // Get the current day of the week (0 for Sunday, 1 for Monday, etc.)
  636. const startOfWeek = new Date(now); // Create a new Date object with the current date and time
  637. // Calculate the difference in milliseconds to the beginning of the week
  638. const diffToMonday = currentDay * 24 * 60 * 60 * 1000; // Subtract 1 day worth of milliseconds for each day after Monday
  639. startOfWeek.setTime(now.getTime() - diffToMonday); // Set the time to the beginning of the week (Monday at 00:00:00)
  640. startOfWeek.setHours(0)
  641. startOfWeek.setMinutes(0)
  642. startOfWeek.setSeconds(0)
  643. startOfWeek.setMilliseconds(0)
  644. const timestamp = startOfWeek.getTime(); // Get the timestamp in milliseconds
  645. return timestamp
  646. }
  647. //hh:mm转换成秒数
  648. static timestringToSeconds = (strTime: string) => {
  649. var list = strTime.split(':')
  650. return parseInt(list[0]) * 3600 + parseInt(list[1]) * 60
  651. }
  652. static tzTimeFormateLocalTime = (timestamp: number, timeZone: string, formate: string) => {
  653. if (!timeZone || timeZone.length == 0) {
  654. return dayjs(timestamp).format(formate)
  655. }
  656. if (process.env.TARO_ENV == 'weapp') {
  657. return dayjs(timestamp).tz(timeZone).format(formate)
  658. }
  659. else {
  660. if (kIsIOS) {
  661. return dayjs(timestamp).tz(timeZone).format(formate)
  662. }
  663. var moment = require('moment-timezone');
  664. return moment(timestamp).tz(timeZone).format(formate)
  665. }
  666. }
  667. static dayjsFormat = (timestamp: number, showToday = false) => {
  668. const today = dayjs();
  669. const dt = dayjs(timestamp);
  670. var strTime = dt.format('HH:mm ')
  671. const yesterday = today.subtract(1, 'day');
  672. const tomorrow = today.subtract(-1, 'day');
  673. if (dt.isSame(today, 'day')) {
  674. if (showToday) {
  675. if (global.language == 'en') return 'Today ' + strTime;
  676. return '今天 ' + strTime
  677. }
  678. return strTime;
  679. } else if (dt.isSame(yesterday, 'day')) {
  680. if (global.language == 'en') return 'Yesterday ' + strTime;
  681. return '昨天 ' + strTime;
  682. } else if (dt.isSame(tomorrow, 'day')) {
  683. if (global.language == 'en') return 'Tomorrow ' + strTime;
  684. return '明天 ' + strTime;
  685. } else {
  686. if (global.language == 'en') return dt.format('MMM DD ') + strTime;
  687. return dt.format('MMMDD日 ') + strTime;
  688. }
  689. }
  690. static tzNameToGMT = (timeZone: string) => {
  691. var minutes = 0
  692. if (!timeZone || timeZone.length == 0) {
  693. minutes = dayjs().utcOffset()
  694. }
  695. if (process.env.TARO_ENV == 'weapp' || kIsIOS) {
  696. minutes = dayjs().tz(timeZone).utcOffset()
  697. }
  698. else {
  699. var moment = require('moment-timezone');
  700. minutes = moment().tz(timeZone).utcOffset()
  701. }
  702. const offsetHours = Math.abs(Math.floor(minutes / 60));
  703. const offsetMinutesRemaining = Math.abs(minutes % 60);
  704. // 构建 GMT 格式的字符串
  705. let gmt = 'GMT';
  706. if (minutes < 0) {
  707. gmt += '+';
  708. } else {
  709. gmt += '-';
  710. }
  711. gmt += `${offsetHours.toString().padStart(2, '0')}:${offsetMinutesRemaining.toString().padStart(2, '0')}`;
  712. return gmt;
  713. }
  714. static tzLocalTime = (timestamp: number, timeZone: string) => {
  715. if (!timeZone || timeZone.length == 0) {
  716. return dayjs(timestamp)
  717. }
  718. if (process.env.TARO_ENV == 'weapp') {
  719. return dayjs(timestamp).tz(timeZone)
  720. }
  721. else {
  722. var moment = require('moment-timezone');
  723. return moment(timestamp).tz(timeZone)
  724. }
  725. }
  726. static isToday = (timestamp: number) => {
  727. if (dayjs().format('YYYY-MM-DD') == dayjs(timestamp).format('YYYY-MM-DD')) {
  728. return true
  729. }
  730. return false
  731. }
  732. static isYesterday = (timestamp: number) => {
  733. if (dayjs().format('YYYY-MM-DD') == dayjs(timestamp + 24 * 3600 * 1000).format('YYYY-MM-DD')) {
  734. return true
  735. }
  736. return false
  737. }
  738. static dayTagText = (begin: number, end: number) => {
  739. const date1 = dayjs(begin);
  740. const date2 = dayjs(end);
  741. // 获取日期部分(去掉时间)
  742. const startDate = date1.startOf('day');
  743. const endDate = date2.startOf('day');
  744. const days = endDate.diff(startDate, 'day')
  745. if (days > 0)
  746. return '+' + days+(global.language=='en'?'d':'天');
  747. return ''
  748. }
  749. }