util.js 1.0 KB

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