FormateDate.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. const FormateDate = (date, fmt = 'YYYY-MM-DD HH:mm:ss') => {
  2. if (!date) {
  3. return ''
  4. }
  5. if (typeof date === 'string') {
  6. date = new Date(date.replace(/-/g, '/'))
  7. }
  8. if (typeof date === 'number') {
  9. date = new Date(date)
  10. }
  11. let o = {
  12. 'M+': date.getMonth() + 1,
  13. 'D+': date.getDate(),
  14. 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  15. 'H+': date.getHours(),
  16. 'm+': date.getMinutes(),
  17. 's+': date.getSeconds(),
  18. 'q+': Math.floor((date.getMonth() + 3) / 3),
  19. 'S': date.getMilliseconds()
  20. }
  21. let week = {
  22. '0': '\u65e5',
  23. '1': '\u4e00',
  24. '2': '\u4e8c',
  25. '3': '\u4e09',
  26. '4': '\u56db',
  27. '5': '\u4e94',
  28. '6': '\u516d'
  29. }
  30. if (/(Y+)/.test(fmt)) {
  31. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  32. }
  33. if (/(E+)/.test(fmt)) {
  34. fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
  35. }
  36. for (var k in o) {
  37. if (new RegExp('(' + k + ')').test(fmt)) {
  38. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  39. }
  40. }
  41. return fmt
  42. }
  43. export default FormateDate;