js获取选中日期的当周的周一和周日
第一种方法(推荐):
function getWeekStr(str) {
// 将字符串转为标准时间格式
str2 = Date.parse(str);
let date = new Date(str2);
let month = date.getMonth() + 1;
let week = getWeekFromDate(date);
if (week === 0) {//第0周归于上月的最后一周
month = date.getMonth();
let dateLast = new Date();
let dayLast = new Date(dateLast.getFullYear(), dateLast.getMonth(), 0).getDate();
let timestamp = new Date(new Date().getFullYear(), new Date().getMonth() - 1, dayLast);
week = getWeekFromDate(new Date(timestamp));
}
let time = month + "月第" + week + "周";
return time;
} function getWeekFromDate(date) {
// 将字符串转为标准时间格式
let w = date.getDay();//周几
if (w === 0) {
w = 7;
}
let week = Math.ceil((date.getDate() + 6 - w) / 7) - 1;
return week;
} console.log("2018-02-3---" + getWeekStr("2018-02-3"));
console.log("2018-02-4---" + getWeekStr("2018-02-4"));
console.log("2018-02-5---" + getWeekStr("2018-02-5"));
console.log("2018-02-12---" + getWeekStr("2018-02-12"));
console.log("2018-02-19---" + getWeekStr("2018-02-19"));
console.log("2018-02-28---" + getWeekStr("2018-02-28"));
console.log("2018-03-1---" + getWeekStr("2018-03-1"));
console.log("2018-03-5---" + getWeekStr("2018-11-1"));
console.log("2018-08-27---" + getWeekStr("2018-12-01"));
第二种方法(比较复杂):
console.log(getNowDateAndNowWeek(1539187200000)); /**
* 获取当月的第几周
* a = d = 当前日期
* b = 6 - w = 当前周的还有几天过完(不算今天)
* a + b 的和在除以7 就是当天是当前月份的第几周
*/
function getMonthWeek(a, b, c) { var date = new Date(a, parseInt(b) - 1, c), w = date.getDay(), d = date.getDate();
return Math.ceil(
(d + 6 - w) / 7
);
}; /**
* 获取选择当前的第几周,当前的周一、周日
* time 选择日期的时间戳
*/
function getNowDateAndNowWeek(time) {
//选中的时间戳
var timestamp = time;
var serverDate = new Date(time); //本周周日的的时间
var sundayTiem = timestamp + ((7 - serverDate.getDay()) * 24 * 60 * 60 * 1000)
var SundayData = new Date(sundayTiem);
//年
var tomorrowY = SundayData.getFullYear();
//月
var tomorrowM = (SundayData.getMonth() + 1 < 10 ? '0' + (SundayData.getMonth() + 1) : SundayData.getMonth() + 1);
//日
var tomorrowD = SundayData.getDate() < 10 ? '0' + SundayData.getDate() : SundayData.getDate();
console.log('周日: ' + tomorrowY + '-' + tomorrowM + '-' + tomorrowD); // 本周周一的时间
var mondayTime = timestamp - ((serverDate.getDay() - 1) * 24 * 60 * 60 * 1000)
var mondayData = new Date(mondayTime);
//年
var mondayY = mondayData.getFullYear();
//月
var mondayM = (mondayData.getMonth() + 1 < 10 ? '0' + (mondayData.getMonth() + 1) : mondayData.getMonth() + 1);
//日
var mondayD = mondayData.getDate() < 10 ? '0' + mondayData.getDate() : mondayData.getDate();
var nowWeek = getMonthWeek(tomorrowY, tomorrowM, tomorrowD);
//输出值
var config = {
SunDay: tomorrowY + '/' + tomorrowM + '/' + tomorrowD,
Monday: mondayY + '/' + mondayM + '/' + mondayD,
nowWeek: nowWeek
}
return config;
}