JS实现获取当前所在周的周六、周⽇⽰例分析
本⽂实例讲述了JS实现获取当前所在周的周六、周⽇。分享给⼤家供⼤家参考,具体如下:
需求:⽆论当前是哪⼀天,获取当天所在周的周末是哪⼀天
实现步骤:
⽐如,今天周⼀,则周⽇距离今天还有(7-1)=6天,那么将今天的时间(毫秒数),加上六天后的时间(6*_dayLongTime 毫秒数),然后根据date函数,转换为⼏⽉⼏⽇。
1、获取当天的时间
let _nowTime=new Date().getTime();
2、获取当天是星期⼏
let _week=_Day();
3、设置⼀天的时长
let _dayLongTime=24*60*60*1000;
4、获取周六周⽇距离现在还有多少毫秒
let _furtureSundayTimes = _nowTime + (7 - _week) * _dayLongTime;
let _furtureSaturdayTimes = _nowTime + (6 - _week) * _dayLongTime;
5、将毫秒数转为date对象
_furtureSundayTimes = new Date(_furtureSundayTimes);
_furtureSaturdayTimes = new Date(_furtureSaturdayTimes);
6、根据⽇期获取⼏⽉⼏⽇
// staurday
let _satYear = _FullYear();
let _satMonth = _Month() + 1;
let _satDay = _Date();
/
/sunday
let _sunYear = _FullYear();
let _sunMonth = _Month() + 1;
let _sunDay = _Date();
7、格式化
_satMonth = _satMonth >= 10 ? _satMonth : '0' + _satMonth;
_satDay = _satDay >= 10 ? _satDay : '0' + _satDay;js当前日期加一天
_sunMonth = _sunMonth >= 10 ? _sunMonth : '0' + _sunMonth;
_sunDay = _sunDay >= 10 ? _sunDay : '0' + _sunDay;
_mealSunDay = _satYear+'-'+_satMonth+'-'+_satDay;
_mealSaturDay = _sunYear+ '-'+_sunMonth+'-'+_sunDay;
8、注:之所以不仅获取周六,然后周⽇则⽤周六加1,就⾏,因为很有可能改周末不在同⼀个⽉份,⽐如3.31周六,4.01周⽇,⽉份不相同
9、⽅法体
function getWeekDay() {
let _date = new Date();
let _nowTime = _Time();
let _week = _Day();
let _dayLongTime = 24 * 60 * 60 * 1000;
let _furtureSundayTimes = _nowTime + (7 - _week) * _dayLongTime;
let _furtureSaturdayTimes = _nowTime + (6 - _week) * _dayLongTime;
_furtureSundayTimes = new Date(_furtureSundayTimes);
_furtureSaturdayTimes = new Date(_furtureSaturdayTimes);
// staurday
let _satYear = _FullYear();
let _satMonth = _Month() + 1;
let _satDay = _Date();
//sunday
let _sunYear = _FullYear();
let _sunMonth = _Month() + 1;
let _sunDay = _Date();
_satMonth = _satMonth >= 10 ? _satMonth : '0' + _satMonth;
_satDay = _satDay >= 10 ? _satDay : '0' + _satDay;
_sunMonth = _sunMonth >= 10 ? _sunMonth : '0' + _sunMonth;
_sunDay = _sunDay >= 10 ? _sunDay : '0' + _sunDay;
_mealSunDay = _satYear+'-'+_satMonth+'-'+_satDay;
_mealSaturDay = _sunYear+ '-'+_sunMonth+'-'+_sunDay;
let _weekendDay = [{
saturDay: _mealSunDay
}, {
sunDay: _mealSaturDay
}]
return _weekendDay;
}
PS:这⾥再为⼤家推荐⼏款时间及⽇期相关⼯具供⼤家参考使⽤:
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家JavaScript程序设计有所帮助。