dateUtil.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * 日期时间格式化
  3. * @param {Date} date 要格式化的日期对象
  4. * @param {String} fmt 格式化字符串,eg:YYYY-MM-DD HH:mm:ss
  5. * @returns 格式化后的日期字符串
  6. */
  7. function formatDate(date, fmt) {
  8. if (typeof date == 'string') {
  9. date = new Date(handleDateStr(date));
  10. }
  11. const o = {
  12. 'M+': date.getMonth() + 1, // 月份
  13. 'd+': date.getDate(), // 日
  14. 'D+': date.getDate(), // 日
  15. 'H+': date.getHours(), // 小时
  16. 'h+': date.getHours(), // 小时
  17. 'm+': date.getMinutes(), // 分
  18. 's+': date.getSeconds(), // 秒
  19. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  20. S: date.getMilliseconds() // 毫秒
  21. };
  22. if (/([y|Y]+)/.test(fmt)) {
  23. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').slice(4 - RegExp.$1.length));
  24. }
  25. for (const k in o) {
  26. if (new RegExp('(' + k + ')').test(fmt)) {
  27. fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).slice(('' + o[k]).length));
  28. }
  29. }
  30. return fmt;
  31. }
  32. /**
  33. * 处理时间字符串,兼容ios下new Date()返回NaN问题
  34. * @param {*} dateStr 日期字符串
  35. * @returns
  36. */
  37. function handleDateStr(dateStr) {
  38. return dateStr.replace(/\-/g, '/');
  39. }
  40. /**
  41. * 判断日期1是否在日期2之前,即日期1小于日期2
  42. * @param {Date} date1
  43. * @param {Date} date2
  44. * @returns
  45. */
  46. function isBefore(date1, date2) {
  47. if (typeof date1 == 'string') {
  48. date1 = new Date(handleDateStr(date1));
  49. }
  50. if (typeof date2 == 'string') {
  51. date2 = new Date(handleDateStr(date2));
  52. }
  53. return date1.getTime() < date2.getTime();
  54. }
  55. /**
  56. * 判断日期1是否在日期2之后,即日期1大于日期2
  57. * @param {Date} date1
  58. * @param {Date} date2
  59. * @returns
  60. */
  61. function isAfter(date1, date2) {
  62. if (typeof date1 == 'string') {
  63. date1 = new Date(handleDateStr(date1));
  64. }
  65. if (typeof date2 == 'string') {
  66. date2 = new Date(handleDateStr(date2));
  67. }
  68. return date1.getTime() > date2.getTime();
  69. }
  70. /**
  71. * 检查传入的字符串是否能转换为有效的Date对象
  72. * @param {String} date
  73. * @returns {Boolean}
  74. */
  75. function isValid(date) {
  76. return new Date(date) !== 'Invalid Date' && !isNaN(new Date(date));
  77. }
  78. export default {
  79. formatDate,
  80. handleDateStr,
  81. isBefore,
  82. isAfter,
  83. isValid
  84. };