datetime.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * 时间格式化
  3. *
  4. * @param time 时间
  5. * @param fmt 格式
  6. * @returns 格式化后的时间
  7. */
  8. const formatTimestamp = (timestamp: number, fmt = 'yyyy-MM-dd HH:mm:ss'): string => {
  9. if (!timestamp) {
  10. return ''
  11. }
  12. const time = new Date(timestamp)
  13. const dict: { [key: string]: any } = {
  14. yyyy: time.getFullYear(),
  15. M: time.getMonth() + 1,
  16. d: time.getDate(),
  17. H: time.getHours(),
  18. m: time.getMinutes(),
  19. s: time.getSeconds(),
  20. w: time.getDay(),
  21. MM: ('' + (time.getMonth() + 101)).substring(1),
  22. dd: ('' + (time.getDate() + 100)).substring(1),
  23. HH: ('' + (time.getHours() + 100)).substring(1),
  24. mm: ('' + (time.getMinutes() + 100)).substring(1),
  25. ss: ('' + (time.getSeconds() + 100)).substring(1),
  26. SSS: ('' + (time.getMilliseconds() + 1000)).substring(1),
  27. WW: getWeek(time.getDay())
  28. }
  29. return fmt.replace(/(yyyy|MM?|dd?|HH?|mm?|ss?|SSS?|WW?)/g, function () {
  30. // eslint-disable-next-line prefer-rest-params
  31. return dict[arguments[0]]
  32. })
  33. }
  34. /**
  35. * 获取大写周数
  36. *
  37. * @param week 一周中的第几天
  38. * @returns 大写周数
  39. */
  40. const getWeek = (week: number): string => {
  41. switch (week) {
  42. case 0:
  43. return '日'
  44. case 1:
  45. return '一'
  46. case 2:
  47. return '二'
  48. case 3:
  49. return '三'
  50. case 4:
  51. return '四'
  52. case 5:
  53. return '五'
  54. case 6:
  55. return '六'
  56. default:
  57. return ''
  58. }
  59. }
  60. export { formatTimestamp, getWeek }