小聂子客栈

常用日期操作集合(持续更新08.22)

热度

项目中常用到对于日期的处理事件


1. 时间戳转换成日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let Timer = (_chuo, has_time, has_second) => {// 时间戳转换
/*
* @param {number} *_chuo 时间戳
* @param {boolean} has_time 是否具体到时分
* @param {boolean} has_second 是否具体到秒
*/
if (!_chuo) {
return _chuo
}
let times = new Date(parseInt(_chuo));
let time_y = times.getFullYear(),
time_M = (times.getMonth() + 1 < 10 ? '0' + (times.getMonth() + 1) : times.getMonth() + 1),
time_d = (times.getDate() < 10 ? '0' + times.getDate() : times.getDate()),
time_h = (times.getHours() < 10 ? '0' + times.getHours() : times.getHours()),
time_m = (times.getMinutes() < 10 ? '0' + times.getMinutes() : times.getMinutes()),
time_s = (times.getSeconds() < 10 ? '0' + times.getSeconds() : times.getSeconds());
let str = time_y + "-" + time_M + "-" + time_d;
if (has_time) {
let t = str + " " + time_h + ":" + time_m;
return has_second ? t + ":" + time_s : t
} else {
return str;
}
};

2. 两个日期相差天数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 初始化日期
let startTime = '2019-05-10',
endTime = '2019-06-18';
let getDiffDays = (_start, _end) => {
// 获取时间戳事件
let get_timer = (str) => {
return new Date(str).getTime();
};
let t1 = get_timer(_start),
t2 = get_timer(_end),
oneDayTime = 1000*60*60*24,// 一天的毫秒数
diffDays = Math.floor((t1 - t2)/oneDayTime);// 相差天数
return Math.abs(diffDays);// 返回绝对值
};
getDiffDays(startTime, endTime)

3. 获取几天后的日期

1
2
3
4
5
6
7
8
9
Date.prototype.offDays = function(days){
let _date = new Date(this.valueOf());// 当前日期
_date.setDate(_date.getDate() + days);
return _date;
}
// 示例
new Date().offDays(3)// 三天后
new Date().offDays(-3)// 三天前
new Date("2019-06-18").offDays(-10)//2019-06-18的十天后

4. 当天是本月第几周

在网上找的两种方法,但是都会有点误差,相对来说用第一种

action 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let getMonthWeek = (str) => {
/*
y = s = 当前日期
m = 6 - w = 当前周的还有几天过完(不算今天)
y + m 的和在除以7 就是当天是当前月份的第几周
*/
let arr = str.split("-");
let [y, m, d] = arr;// 分别对应年,月,日
let _date = new Date(y, parseInt(m) - 1, d),
w = _date.getDay(),
s = _date.getDate();
return Math.ceil((s + 6 - w) / 7)
};
getMonthWeek("2019-06-18")

action 2:

1
2
3
4
5
6
7
8
9
10
11
let getMonthWeek = (str) => {
let week = Math.ceil(str.getDate()/7),
month = str.getMonth() + 1;// 该日期为第几周
// 判断这个月前7天是周几,如果不是周一,则计入上个月
if(str.getDate() < 7){
if(str.getDay() !== 1){
week = 5;
}
}
return week;
}


5. 所在月的最后一天

有个瑕疵,如果当前是1月份末尾几天,对应的下个月就会跳到3月份,所以获取到的日期是2月份的最后一天

1
2
3
4
5
6
let getMonthLast = (str) => {
let _end = new Date(str);
_end.setMonth(_end.getMonth + 1);// 设置成下一个月的同一天
_end.setDate(0);// 设0 =》 起始天 =》 上个月最后一天
return _end;
}


6. 两个日期相隔月份

1
2
3
4
5
6
7
8
function getMonthInterval(_date){
// _date为两个日期的数组,如:['2019-05-11', '2019-08-22']
let _start = new Date(_date[0]),
_end = new Date(_date[1]);
let yearToMonth = (_end.getFullYear() - _start.getFullYear())*12,// 相隔年份 * 12
monthToMonth = _end.getMonth() - _start.getMonth();// 单独月份相差
return parseInt(yearToMonth + monthToMonth);
};

扫描二维码,分享此文章