dateUtil.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * Independent time operation tool to facilitate subsequent switch to dayjs
  3. */
  4. // TODO 芋艿:【锁屏】可能后面删除掉
  5. import dayjs from 'dayjs'
  6. const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
  7. const DATE_FORMAT = 'YYYY-MM-DD'
  8. export function formatToDateTime(date?: dayjs.ConfigType, format = DATE_TIME_FORMAT): string {
  9. return dayjs(date).format(format)
  10. }
  11. export function formatToDate(date?: dayjs.ConfigType, format = DATE_FORMAT): string {
  12. return dayjs(date).format(format)
  13. }
  14. export function parseTime(time, pattern) {
  15. if (arguments.length === 0 || !time) {
  16. return null
  17. }
  18. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  19. let date
  20. if (typeof time === 'object') {
  21. date = time
  22. } else {
  23. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  24. time = parseInt(time)
  25. } else if (typeof time === 'string') {
  26. time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
  27. }
  28. if ((typeof time === 'number') && (time.toString().length === 10)) {
  29. time = time * 1000
  30. }
  31. date = new Date(time)
  32. }
  33. const formatObj = {
  34. y: date.getFullYear(),
  35. m: date.getMonth() + 1,
  36. d: date.getDate(),
  37. h: date.getHours(),
  38. i: date.getMinutes(),
  39. s: date.getSeconds(),
  40. a: date.getDay()
  41. }
  42. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  43. let value = formatObj[key]
  44. // Note: getDay() returns 0 on Sunday
  45. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
  46. if (result.length > 0 && value < 10) {
  47. value = '0' + value
  48. }
  49. return value || 0
  50. })
  51. return time_str
  52. }
  53. export const dateUtil = dayjs