×

实现时间效果:无论当前是哪一天,获取当天所在周的周末是哪一天

作者:andy0012020.09.14来源:Web前端之家浏览:4408评论:0
关键词:js

比如,今天周一,则周日距离今天还有(7-1)=6天,那么将今天的时间(毫秒数),加上六天后的时间(6*_dayLongTime 毫秒数),然后根据date函数,转换为几月几日。

获取当天的时间。

let _nowTime=new Date().getTime();

获取当天是星期几

let _week=_date.getDay();

设置一天的时长

let _dayLongTime=24*60*60*1000;

获取周六周日距离现在还有多少毫秒

let _furtureSundayTimes = _nowTime + (7 - _week) * _dayLongTime;
let _furtureSaturdayTimes = _nowTime + (6 - _week) * _dayLongTime;

将毫秒数转为date对象

_furtureSundayTimes = new Date(_furtureSundayTimes);
_furtureSaturdayTimes = new Date(_furtureSaturdayTimes);

根据日期获取几月几日

// staurday
let _satYear = _furtureSaturdayTimes.getFullYear();
let _satMonth = _furtureSaturdayTimes.getMonth() + 1;
let _satDay = _furtureSaturdayTimes.getDate();
//sunday
let _sunYear = _furtureSundayTimes.getFullYear();
let _sunMonth = _furtureSundayTimes.getMonth() + 1;
let _sunDay = _furtureSundayTimes.getDate();

格式化

_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;

注:之所以不仅获取周六,然后周日则用周六加1,就行,因为很有可能改周末不在同一个月份,比如3.31周六,4.01周日,月份不相同

方法体

function getWeekDay() {
 let _date = new Date();
 let _nowTime = _date.getTime();
 let _week = _date.getDay();
 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 = _furtureSaturdayTimes.getFullYear();
 let _satMonth = _furtureSaturdayTimes.getMonth() + 1;
 let _satDay = _furtureSaturdayTimes.getDate();
 //sunday
 let _sunYear = _furtureSundayTimes.getFullYear();
 let _sunMonth = _furtureSundayTimes.getMonth() + 1;
 let _sunDay = _furtureSundayTimes.getDate();
 _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;
}

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js202009124a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: