ruoyi.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * 通用js方法封装处理
  3. * Copyright (c) 2019 ruoyi
  4. */
  5. // 日期格式化
  6. export function parseTime(time, pattern) {
  7. if (arguments.length === 0 || !time) {
  8. return null
  9. }
  10. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  11. let date
  12. if (typeof time === 'object') {
  13. date = time
  14. } else {
  15. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  16. time = parseInt(time)
  17. } else if (typeof time === 'string') {
  18. time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm),'');
  19. }
  20. if ((typeof time === 'number') && (time.toString().length === 10)) {
  21. time = time * 1000
  22. }
  23. date = new Date(time)
  24. }
  25. const formatObj = {
  26. y: date.getFullYear(),
  27. m: date.getMonth() + 1,
  28. d: date.getDate(),
  29. h: date.getHours(),
  30. i: date.getMinutes(),
  31. s: date.getSeconds(),
  32. a: date.getDay()
  33. }
  34. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  35. let value = formatObj[key]
  36. // Note: getDay() returns 0 on Sunday
  37. if (key === 'a') {
  38. return ['日', '一', '二', '三', '四', '五', '六'][value]
  39. }
  40. if (result.length > 0 && value < 10) {
  41. value = '0' + value
  42. }
  43. return value || 0
  44. })
  45. return time_str
  46. }