js獲取昨天,最近7天,最近30天通用方法


 1 function formatDate (val) {
 2   // 格式化時間
 3   let start = new Date(val)
 4   let y = start.getFullYear()
 5   let m = (start.getMonth() + 1) > 10 ? (start.getMonth() + 1) : '0' + (start.getMonth() + 1)
 6   let d = start.getDate() > 10 ? start.getDate() : '0' + start.getDate()
 7   return y + '-' + m + '-' + d
 8 }
 9 
10 function mistiming (sDate1, sDate2) {
11   // 計算開始和結束的時間差
12   let aDate, oDate1, oDate2, iDays
13   aDate = sDate1.split('-')
14   oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
15   aDate = sDate2.split('-')
16   oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
17   iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24)
18   return iDays + 1
19 }
20 
21 function countDate (start, end) {
22   // 判斷開始和結束之間的時間差是否在90天內
23   let days = mistiming(start, end)
24   let stateT = days > 90 ? Boolean(0) : Boolean(1)
25   return {
26     state: stateT,
27     day: days
28   }
29 }46 
47 function timeForMat (count) {
48   // 拼接時間
49   let time1 = new Date()
50   time1.setTime(time1.getTime() - (24 * 60 * 60 * 1000))
51   let Y1 = time1.getFullYear()
52   let M1 = ((time1.getMonth() + 1) > 10 ? (time1.getMonth() + 1) : '0' + (time1.getMonth() + 1))
53   let D1 = (time1.getDate() > 10 ? time1.getDate() : '0' + time1.getDate())
54   let timer1 = Y1 + '-' + M1 + '-' + D1 // 當前時間
55   let time2 = new Date()
56   time2.setTime(time2.getTime() - (24 * 60 * 60 * 1000 * count))
57   let Y2 = time2.getFullYear()
58   let M2 = ((time2.getMonth() + 1) > 10 ? (time2.getMonth() + 1) : '0' + (time2.getMonth() + 1))
59   let D2 = (time2.getDate() > 10 ? time2.getDate() : '0' + time2.getDate())
60   let timer2 = Y2 + '-' + M2 + '-' + D2 // 之前的7天或者30天
61   return {
62     t1: timer1,
63     t2: timer2
64   }
65 }
66 
67 function yesterday (start, end) {
68   // 校驗是不是選擇的昨天
69   let timer = timeForMat(1)
70   return timer
71 }
72 
73 function sevenDays () {
74   // 獲取最近7天
75   let timer = timeForMat(7)
76   return timer
77 }
78 
79 function thirtyDays () {
80   // 獲取最近30天
81   let timer = timeForMat(30)
82   return timer
83 }
84 
85 export {
86   formatDate,
87   countDate,89   yesterday,
90   sevenDays,
91   thirtyDays
92 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM