time.ts 861 B

12345678910111213141516171819202122232425262728293031
  1. export function parseTime(time, cFormat = '{y}-{m}-{d} {h}:{i}:{s}') {
  2. if (arguments.length === 0) {
  3. return null
  4. }
  5. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  6. let date
  7. if (typeof time === 'object') {
  8. date = time
  9. } else {
  10. if (('' + time).length === 10) time = parseInt(time) * 1000
  11. date = new Date(time)
  12. }
  13. const formatObj = {
  14. y: date.getFullYear(),
  15. m: date.getMonth() + 1,
  16. d: date.getDate(),
  17. h: date.getHours(),
  18. i: date.getMinutes(),
  19. s: date.getSeconds(),
  20. a: date.getDay()
  21. }
  22. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  23. let value = formatObj[key]
  24. if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
  25. if (result.length > 0 && value < 10) {
  26. value = '0' + value
  27. }
  28. return value || 0
  29. })
  30. return time_str
  31. }