javascript 获取本周第一天和最后一天

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>查询</title>
<style>
label{
line-height: 25px;
}
</style>

</head>

<body>

</body>
</html>
<script>
window.onload=function (){
alert(getCurrentWeekFirstDay(new Date()))
alert(getCurrentWeekLastDay(new Date()))
}
function getCurrentWeekFirstDay(date) {
let weekFirstDay = new Date(date - (date.getDay() - 1) * 86400000)
let firstMonth = Number(weekFirstDay.getMonth()) + 1

if (firstMonth < 10) {
firstMonth = '0' + firstMonth
}
let weekFirstDays = weekFirstDay.getDate();
if (weekFirstDays < 10) {
weekFirstDays = '0' + weekFirstDays;
}
return weekFirstDay.getFullYear() + '-' + firstMonth + '-' + weekFirstDays;
}
/**
* 获取本周的最后一天
* 返回格式: YYYY-mm-dd
* 例子: 当日为: 2020-11-27
* 返回日期为: 2020-11-29
* */
function getCurrentWeekLastDay(date) {
let weekFirstDay = new Date(date - (date.getDay() - 1) * 86400000)
let weekLastDay = new Date((weekFirstDay / 1000 + 6 * 86400) * 1000)
let lastMonth = Number(weekLastDay.getMonth()) + 1
if (lastMonth < 10) {
lastMonth = '0' + lastMonth
}
let weekLastDays = weekLastDay.getDate();
if (weekLastDays < 10) {
weekLastDays = '0' + weekLastDays;
}
return weekFirstDay.getFullYear() + '-' + lastMonth + '-' + weekLastDays;
}
</script>

posted @ 2021-11-24 13:53  HalleyZ  阅读(1057)  评论(0编辑  收藏  举报