dateFunc.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. let shortMonth = [
  2. 'Jan',
  3. 'Feb',
  4. 'Mar',
  5. 'Apr',
  6. 'May',
  7. 'Jun',
  8. 'Jul',
  9. 'Aug',
  10. 'Sep',
  11. 'Oct',
  12. 'Nov',
  13. 'Dec'
  14. ]
  15. let defMonthNames = [
  16. 'January',
  17. 'February',
  18. 'March',
  19. 'April',
  20. 'May',
  21. 'June',
  22. 'July',
  23. 'August',
  24. 'September',
  25. 'October',
  26. 'November',
  27. 'December'
  28. ]
  29. let dateFunc = {
  30. getDuration(date) {
  31. // how many days of this month
  32. let dt = new Date(date)
  33. let month = dt.getMonth();
  34. dt.setMonth(dt.getMonth() + 1)
  35. dt.setDate(0);
  36. return dt.getDate()
  37. },
  38. changeDay(date, num) {
  39. let dt = new Date(date)
  40. return new Date(dt.setDate(dt.getDate() + num))
  41. },
  42. getStartDate(date) {
  43. // return first day of this month
  44. // console.log(new Date(date.getFullYear(), date.getMonth(), 1,0,0))
  45. return new Date(date.getFullYear(), date.getMonth(), 1)
  46. },
  47. getEndDate(date) {
  48. // get last day of this month
  49. let dt = new Date(date.getFullYear(), date.getMonth() + 1, 1, 0, 0) // 1st day of next month
  50. return new Date(dt.setDate(dt.getDate() - 1)) // last day of this month
  51. },
  52. // 获取当前周日期数组
  53. getDates(date) {
  54. let new_Date = date
  55. let timesStamp = new Date(new_Date.getFullYear(), new_Date.getMonth(), new_Date.getDate(), 0, 0, 0).getTime()
  56. // let timesStamp = new_Date.getTime();
  57. let currenDay = new_Date.getDay();
  58. let dates = [];
  59. for (let i = 0; i < 7; i++) {
  60. dates.push(new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)));
  61. }
  62. return dates
  63. },
  64. format(date, format, monthNames) {
  65. monthNames = monthNames || defMonthNames
  66. if (typeof date === 'string') {
  67. date = new Date(date.replace(/-/g, '/'))
  68. } else {
  69. date = new Date(date)
  70. }
  71. let map = {
  72. 'M': date.getMonth() + 1,
  73. 'd': date.getDate(),
  74. 'h': date.getHours(),
  75. 'm': date.getMinutes(),
  76. 's': date.getSeconds(),
  77. 'q': Math.floor((date.getMonth() + 3) / 3),
  78. 'S': date.getMilliseconds()
  79. }
  80. format = format.replace(/([yMdhmsqS])+/g, (all, t) => {
  81. let v = map[t]
  82. if (v !== undefined) {
  83. if (all === 'MMMM') {
  84. return monthNames[v - 1]
  85. }
  86. if (all === 'MMM') {
  87. return shortMonth[v - 1]
  88. }
  89. if (all.length > 1) {
  90. v = '0' + v
  91. v = v.substr(v.length - 2)
  92. }
  93. return v
  94. } else if (t === 'y') {
  95. return String(date.getFullYear()).substr(4 - all.length)
  96. }
  97. return all
  98. })
  99. return format
  100. }
  101. }
  102. module.exports = dateFunc