date.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * 时间格式化函数(将时间格式化为,2019年08月12日,2019-08-12,2019/08/12的形式)
  3. * pattern参数(想要什么格式的数据就传入什么格式的数据)
  4. * · 'yyyy-MM-dd' ---> 输出如2019-09-20
  5. * · 'yyyy-MM-dd HH:mm' ---> 输出如2019-09-20 18:20
  6. * · 'yyyy-MM-dd HH:mm:ss' ---> 输出如2019-09-20 06:20:23
  7. * · 'yyyy/MM/dd' ---> 输出如2019/09/20
  8. * · 'yyyy年MM月dd日' ---> 输出如2019年09月20日
  9. * · 'yyyy年MM月dd日 HH时mm分' ---> 输出如2019年09月20日 18时20分
  10. * · 'yyyy年MM月dd日 HH时mm分ss秒' ---> 输出如2019年09月20日 18时20分23秒
  11. * · 'yyyy年MM月dd日 HH时mm分ss秒 EE' ---> 输出如2019年09月20日 18时20分23秒 周二
  12. * · 'yyyy年MM月dd日 HH时mm分ss秒 EEE' ---> 输出如2019年09月20日 18时20分23秒 星期二
  13. * 参考: https://www.cnblogs.com/mr-wuxiansheng/p/6296646.html
  14. */
  15. export function dateFormatter(date = '', fmt = 'yyyy-MM-dd HH:mm:ss') {
  16. // 将传入的date转为时间对象
  17. if (!date) return ''
  18. // 处理ios不兼容'2022-6-6'类似的'-'问题
  19. if (typeof data === 'string') {
  20. date = date.replace(/-/g, '/')
  21. }
  22. date = new Date(date)
  23. const o = {
  24. 'y+': date.getFullYear(),
  25. 'M+': date.getMonth() + 1, // 月份
  26. 'd+': date.getDate(), // 日
  27. // 12小时制
  28. 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
  29. // 24小时制
  30. 'H+': date.getHours(), // 小时
  31. 'm+': date.getMinutes(), // 分
  32. 's+': date.getSeconds(), // 秒
  33. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  34. S: date.getMilliseconds(), // 毫秒
  35. 'E+': date.getDay() // 周
  36. }
  37. const week = ['日', '一', '二', '三', '四', '五', '六']
  38. if (/(y+)/.test(fmt)) {
  39. fmt = fmt.replace(
  40. RegExp.$1,
  41. (date.getFullYear() + '').substr(4 - RegExp.$1.length)
  42. )
  43. }
  44. if (/(E+)/.test(fmt)) {
  45. fmt = fmt.replace(
  46. RegExp.$1,
  47. (RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '星期' : '周') : '') +
  48. week[date.getDay()]
  49. )
  50. }
  51. for (const k in o) {
  52. if (new RegExp('(' + k + ')').test(fmt)) {
  53. fmt = fmt.replace(
  54. RegExp.$1,
  55. RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
  56. )
  57. }
  58. }
  59. return fmt
  60. }