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 }

 

posted @ 2017-07-28 16:58  豆浆油条123  阅读(8970)  评论(0编辑  收藏  举报