//获取时间段
var date = new Date();
//标准日期格式yyyy/mm/dd
var weekByDate = date.substring(0, 4) + "/" + date.substring(5, 7) + "/" + date.substring(8, 10);
console.log(getWeekByDay(weekByDate));
//获取日期字符串对应的时间戳
var timestamp = new Date(weekByDate).getTime();
//获取星期几
var currentDay = new Date(weekByDate).getDay();
//获取时间戳
var previousSaturdayTime;
var nextFridayTime;
if (currentDay == 0) {
//获取该天前一个星期六的时间戳
previousSaturdayTime = timestamp- 24 * 60 * 60 * 1000;
//获取该天后一个星期五的时间戳
nextFridayTime = timestamp + (5 - currentDay) * 24 * 60 * 60 * 1000;
} else {
//获取该天前一个星期六的时间戳
previousSaturdayTime = timestamp - (currentDay + 1) * 24 * 60 * 60 * 1000;
//获取该天后一个星期五的时间戳
nextFridayTime = timestamp + (5 - currentDay) * 24 * 60 * 60 * 1000;
}
console.log("前一个星期六的日期---" + getNowFormatDate(previousSaturdayTime));
console.log("后一个星期五的日期---" + getNowFormatDate(nextFridayTime));
/*
*根据日期获取当前星期X(0-6,0代表星期天)
*@param yyyy/mm/dd 标准日期格式
*@returns:星期X
*/
function getWeekByDay(weekByDate) {
var week = new Date(weekByDate).getDay();
//创建星期数组
var weekNum = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
return weekNum[week];
}
/*
*获取当前时间戳的日期字符串
* @param timestamp 时间戳
*@returns:YYYY年MM月DD日
*/
function getNowFormatDate(timestamp) {
var year = new Date(timestamp).getFullYear();
var month = new Date(timestamp).getMonth() + 1;
var date = new Date(timestamp).getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (date >= 0 && date <= 9) {
date = "0" + date;
}
var dateByTime = year + "年" + month + "月" + date + "日";
return dateByTime;
}
js根据某个日期,获取该日期的前一个星期六以及后一个星期五
最新推荐文章于 2021-11-20 16:06:37 发布