time_format.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. export class TimeFormatter {
  2. static nowDuration = 30
  3. //格式化时间
  4. static formatTimestamp(timestamp: number): string {
  5. const currentDate = new Date();
  6. const inputDate = new Date(timestamp);
  7. // 判断是否是今天
  8. if (
  9. inputDate.getDate() === currentDate.getDate() &&
  10. inputDate.getMonth() === currentDate.getMonth() &&
  11. inputDate.getFullYear() === currentDate.getFullYear()
  12. ) {
  13. return `今天 ${TimeFormatter.formatTime(inputDate)}`;
  14. }
  15. // 判断是否是昨天
  16. const yesterday = new Date();
  17. yesterday.setDate(currentDate.getDate() - 1);
  18. if (
  19. inputDate.getDate() === yesterday.getDate() &&
  20. inputDate.getMonth() === yesterday.getMonth() &&
  21. inputDate.getFullYear() === yesterday.getFullYear()
  22. ) {
  23. return `昨天 ${TimeFormatter.formatTime(inputDate)}`;
  24. }
  25. // 判断是否是明天
  26. const tomorrow = new Date();
  27. tomorrow.setDate(currentDate.getDate() + 1);
  28. if (
  29. inputDate.getDate() === tomorrow.getDate() &&
  30. inputDate.getMonth() === tomorrow.getMonth() &&
  31. inputDate.getFullYear() === tomorrow.getFullYear()
  32. ) {
  33. return `明天 ${TimeFormatter.formatTime(inputDate)}`;
  34. }
  35. // 返回 YYYY-MM-DD HH:mm
  36. return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber(
  37. inputDate.getDate()
  38. )} ${TimeFormatter.formatTime(inputDate)}`;
  39. }
  40. static dateTimeFormate(timestamp: number) {
  41. const currentDate = new Date();
  42. const inputDate = new Date(timestamp);
  43. // 判断是否是今天
  44. if (
  45. inputDate.getDate() === currentDate.getDate() &&
  46. inputDate.getMonth() === currentDate.getMonth() &&
  47. inputDate.getFullYear() === currentDate.getFullYear()
  48. ) {
  49. return `今天 ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`;
  50. }
  51. // 判断是否是昨天
  52. const yesterday = new Date();
  53. yesterday.setDate(currentDate.getDate() - 1);
  54. if (
  55. inputDate.getDate() === yesterday.getDate() &&
  56. inputDate.getMonth() === yesterday.getMonth() &&
  57. inputDate.getFullYear() === yesterday.getFullYear()
  58. ) {
  59. return `昨天 ${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`;
  60. }
  61. return TimeFormatter.getDateAndWeek(timestamp)+' '+`${TimeFormatter.padZero(inputDate.getHours())}:${TimeFormatter.padZero(inputDate.getMinutes())}`
  62. }
  63. //1.只显示时间
  64. static timelineFormatTime(timestamp: number, isTestUser?: boolean): string {
  65. if (!timestamp) {
  66. return ' '
  67. }
  68. var date = new Date(timestamp)
  69. // 返回 HH:mm
  70. var str = `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`;
  71. if (isTestUser) {
  72. str += `:${TimeFormatter.formatNumber(date.getSeconds())}`
  73. }
  74. return str
  75. }
  76. //2.基于日期显示日期,省略今天描述
  77. static dateDescription(timestamp: number, showToday?: boolean): string {
  78. if (!timestamp) {
  79. return ''
  80. }
  81. const currentDate = new Date();
  82. const inputDate = new Date(timestamp);
  83. // 判断是否是今天
  84. if (
  85. inputDate.getDate() === currentDate.getDate() &&
  86. inputDate.getMonth() === currentDate.getMonth() &&
  87. inputDate.getFullYear() === currentDate.getFullYear()
  88. ) {
  89. if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000 && currentDate.getTime() - timestamp >= 0) {
  90. return '刚刚'
  91. }
  92. return showToday ? '今天' : ``;
  93. }
  94. // 判断是否是昨天
  95. const yesterday = new Date();
  96. yesterday.setDate(currentDate.getDate() - 1);
  97. if (
  98. inputDate.getDate() === yesterday.getDate() &&
  99. inputDate.getMonth() === yesterday.getMonth() &&
  100. inputDate.getFullYear() === yesterday.getFullYear()
  101. ) {
  102. return `昨天`;
  103. }
  104. // 判断是否是明天
  105. const tomorrow = new Date();
  106. tomorrow.setDate(currentDate.getDate() + 1);
  107. if (
  108. inputDate.getDate() === tomorrow.getDate() &&
  109. inputDate.getMonth() === tomorrow.getMonth() &&
  110. inputDate.getFullYear() === tomorrow.getFullYear()
  111. ) {
  112. return `明天`;
  113. }
  114. const utcDate1 = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate())
  115. const utcDate2 = Date.UTC(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate())
  116. const oneDayMilliseconds = 24 * 60 * 60 * 1000; // 一天的毫秒数
  117. var dayDifference = Math.floor((utcDate2 - utcDate1) / oneDayMilliseconds);
  118. if (dayDifference < 0) {
  119. // dayDifference = 0 - dayDifference;
  120. // return `${dayDifference}天前`
  121. var strDt = ''
  122. if (currentDate.getFullYear() != inputDate.getFullYear()) {
  123. strDt = inputDate.getFullYear() + '年'
  124. }
  125. strDt = strDt + (inputDate.getMonth() + 1) + '月'
  126. strDt = strDt + (inputDate.getDate()) + '日'
  127. return strDt
  128. }
  129. return `${dayDifference}天后`
  130. // return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber(
  131. // inputDate.getDate()
  132. // )}`;
  133. }
  134. //3. datedescription+时间,刚刚时隐藏时间
  135. static datetimeDescription(timestamp: number): string {
  136. const currentDate = new Date();
  137. if (currentDate.getTime() - timestamp <= TimeFormatter.nowDuration * 1000) {
  138. return TimeFormatter.dateDescription(timestamp, true)
  139. }
  140. return TimeFormatter.dateDescription(timestamp, true) + '' + TimeFormatter.timeDescription(timestamp)
  141. }
  142. static timeDescription(timestamp): string {
  143. const date = new Date(timestamp);
  144. return `${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}`;
  145. }
  146. static formatTime(date: Date): string {
  147. return `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}:${TimeFormatter.formatNumber(date.getSeconds())}`;
  148. }
  149. static formatNumber(num: number): string {
  150. return num.toString().padStart(2, '0');
  151. }
  152. static getYearByDate(num: number): string {
  153. return (num + '').substring(0, 4) + '年'
  154. }
  155. static getMonthAndDayByDate(num: number): string {
  156. const dt = new Date((num + '').substring(0, 4) + '/' +
  157. (num + '').substring(4, 6) + '/' +
  158. (num + '').substring(6));
  159. const now = new Date();
  160. const diff = now.getTime() - dt.getTime();
  161. const day = 1000 * 60 * 60 * 24;
  162. if (diff < day) {
  163. return '今天';
  164. } else if (diff < 2 * day) {
  165. return '昨天';
  166. } else {
  167. var month = parseInt((num + '').substring(4, 6))
  168. var date = parseInt((num + '').substring(6, 8))
  169. return month + '月' + date + '日'
  170. }
  171. }
  172. //duration 根据起终点时间,忽略精度,如果两个时间点小于60s,则保留精度,否则为分钟
  173. static durationFormate(startTimestamp: number, endTimestamp: number) {
  174. var start = startTimestamp;
  175. var end = endTimestamp;
  176. const diff = Math.abs(end - start);
  177. if (diff > 60000) {
  178. var startTime = new Date(start)
  179. startTime.setSeconds(0)
  180. startTime.setMilliseconds(0)
  181. var endTime = new Date(end)
  182. endTime.setSeconds(0)
  183. endTime.setMilliseconds(0)
  184. start = startTime.getTime()
  185. end = endTime.getTime()
  186. }
  187. return TimeFormatter.calculateTimeDifference(start, end)
  188. }
  189. //计算时间间隔
  190. static calculateTimeDifference(startTimestamp: number, endTimestamp: number, ingoreSeconds?: boolean): string {
  191. const diff = Math.abs(endTimestamp - startTimestamp);
  192. // 计算小时、分钟和秒数
  193. const hours = Math.floor(diff / (1000 * 60 * 60));
  194. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  195. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  196. // 根据间隔的大小返回不同的格式
  197. if (diff < 60000) {
  198. return `${seconds}秒`;
  199. } else if (diff < 3600000) {
  200. return `${minutes}分钟`;
  201. // return `${minutes}分${seconds}秒`;
  202. } else {
  203. // if (ingoreSeconds) return `${hours}小时${minutes}分钟`;
  204. // return `${hours}小时${minutes}分${seconds}秒`;
  205. if (minutes == 0) {
  206. return `${hours}小时`;
  207. }
  208. return `${hours}小时${minutes}分钟`;
  209. }
  210. }
  211. //格式化时间间隔
  212. static formateTimeDifference(startTimestamp: number, endTimestamp: number, ingoreSeconds?: boolean): string {
  213. const diff = Math.abs(endTimestamp - startTimestamp);
  214. // 计算小时、分钟和秒数
  215. const hours = Math.floor(diff / (1000 * 60 * 60));
  216. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  217. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  218. // 根据间隔的大小返回不同的格式
  219. if (diff < 60000) {
  220. return `00:00:${TimeFormatter.padZero(seconds)}`;
  221. } else if (diff < 3600000) {
  222. return `00:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  223. } else {
  224. if (ingoreSeconds) return `${hours}小时${minutes}分`;
  225. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  226. }
  227. }
  228. static formateTime(timestamp: number) {
  229. const date = new Date(timestamp);
  230. return `${TimeFormatter.padZero(date.getMonth() + 1)}-${TimeFormatter.padZero(date.getDate())} ${TimeFormatter.padZero(date.getHours())}:${TimeFormatter.padZero(date.getMinutes())}:${TimeFormatter.padZero(date.getSeconds())}`;
  231. }
  232. static formateHourMinute(startTimestamp: number, endTimestamp: number): string {
  233. const diff = Math.abs(endTimestamp - startTimestamp);
  234. // 计算小时、分钟和秒数
  235. const hours = Math.floor(diff / (1000 * 60 * 60));
  236. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  237. return (hours < 10 ? `0${hours}` : `${hours}`) + ':' + (minutes < 10 ? `0${minutes}` : `${minutes}`);
  238. }
  239. static countdown = (dt: number): string => {
  240. const end = Date.now();
  241. const time = end > dt ? Math.floor((end - dt) / 1000) : Math.ceil((dt - end) / 1000)//Math.ceil((end>dt?end-dt:dt-end)/1000);
  242. const hours = Math.floor(time / 3600);
  243. const minutes = Math.floor((time % 3600) / 60);
  244. const seconds = Math.floor(time % 60);
  245. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  246. };
  247. //计算正计时
  248. static formateTimeNow = (dt: number): string => {
  249. const end = Date.now();
  250. const time = Math.floor((end > dt ? end - dt : dt - end) / 1000);
  251. const hours = Math.floor(time / 3600);
  252. const minutes = Math.floor((time % 3600) / 60);
  253. const seconds = Math.floor(time % 60);
  254. return `${TimeFormatter.padZero(hours)}:${TimeFormatter.padZero(minutes)}:${TimeFormatter.padZero(seconds)}`;
  255. };
  256. static padZero = (num: number): string => {
  257. return num.toString().padStart(2, '0');
  258. };
  259. //根据时间段和一个时间,推算另外一个时间
  260. static calculateTimeByTimeRange = (timeRange: number, strTime: string, isStart: boolean): string => {
  261. console.log(timeRange, strTime, isStart)
  262. var list = strTime.split(':');
  263. var time = parseInt(list[0]) * 60 + parseInt(list[1]);
  264. if (isStart) {
  265. time = time + timeRange;
  266. }
  267. else {
  268. time = time - timeRange;
  269. }
  270. time = time < 0 ? time + 24 * 60 : time;
  271. time = time >= 24 * 60 ? time - 24 * 60 : time;
  272. var hour = Math.floor(time / 60);
  273. var minute = time % 60;
  274. return `${TimeFormatter.padZero(hour)}:${TimeFormatter.padZero(minute)}`;
  275. }
  276. //获取今天的日期和星期几
  277. static getDateAndWeek = (timestamp: number, ignore = false) => {
  278. const now = new Date();
  279. var dt = new Date(timestamp)
  280. dt.setSeconds(0)
  281. dt.setMilliseconds(0)
  282. dt.setMinutes(0)
  283. dt.setHours(0)
  284. const diff = now.getTime() - dt.getTime();
  285. const day = 1000 * 60 * 60 * 24;
  286. if (diff < day && !ignore) {
  287. return '今天';
  288. } else if (diff < 2 * day && !ignore) {
  289. return '昨天';
  290. } else {
  291. var weeks = ['日', '一', '二', '三', '四', '五', '六']
  292. return `${dt.getMonth() + 1}月${dt.getDate()}日 星期${weeks[dt.getDay()]}`
  293. }
  294. }
  295. //获取当前时间(hh:mm)
  296. static getCurrentHourAndMinute = () => {
  297. var now = new Date()
  298. return `${TimeFormatter.padZero(now.getHours())}:${TimeFormatter.padZero(now.getMinutes())}`;
  299. }
  300. }