js获取本周,本月,本年
程序员文章站
2022-06-15 22:50:45
...
// 计算当周
function getDates() {
var data = new Date();
var timesStamp = data.getTime();
console.log(timesStamp)
var currenDay = data.getDay();
var dates = [];
for (var i = 0; i < 7; i++) {
dates.push(
new Date(
timesStamp + 24 * 60 * 60 * 1000 * (i - ((currenDay + 6) % 7)))
.toLocaleDateString()
);
}
return dates
};
//计算当月
function ThisMonth() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var min = new Date(year, month, 1);
var max = new Date(year, month + 1, 0);
return [formatDateTime(min, 'YYYYMMDD'), formatDateTime(max, 'YYYYMMDD')]
};
// 获取本年
function ThisYear() {
var firstDay = new Date();
firstDay.setDate(1);
firstDay.setMonth(0);
var lastDay = new Date();
lastDay.setFullYear(lastDay.getFullYear() + 1);
lastDay.setDate(0);
lastDay.setMonth(-1);
firstDay = formatDateTime(firstDay, 'YYYYMMDD');
lastDay = formatDateTime(lastDay, 'YYYYMMDD');
return [firstDay, lastDay];
};
//日期格式化
function formatDateTime(time, format, YMSign = '-', HSSign = ':') {
let formatDate = '';
function add0(num) {
return num >= 10 ? num : '0' + num;
}
let date = new Date(time);
let year = date.getFullYear();
let mounth = add0(date.getMonth() + 1);
let day = add0(date.getDate());
let hours = add0(date.getHours());
let minutes = add0(date.getMinutes());
let seconds = add0(date.getSeconds());
switch (format) {
case 'YYYY':
formatDate = `${year}`;
break;
case 'YYYY-MM':
formatDate = `${year}${YMSign}${mounth}`;
break;
case 'YYYYMM':
formatDate = `${year}${mounth}`;
break;
case 'YYYY-MM-DD':
formatDate = `${year}${YMSign}${mounth}${YMSign}${day}`;
break;
case 'YYYYMMDD':
formatDate = `${year}${mounth}${day}`;
break;
case 'YYYY-MM-DD HH:MM:SS':
formatDate = `${year}${YMSign}${mounth}${YMSign}${day} ${hours}${HSSign}${minutes}${HSSign}${seconds}`;
break;
default:
formatDate = `${year}${YMSign}${mounth}${YMSign}${day}T${hours}${HSSign}${minutes}${HSSign}${seconds}`;
}
return formatDate;
}
下一篇: redis:详解
推荐阅读
-
用php获取本周,上周,本月,上月,本季度日期的代码
-
获取今天,昨天,本周,上周,本月,上月时间(实例分享)
-
php获取本年、本月、本周时间戳和日期格式的实例代码
-
用php获取本周,上周,本月,上月,本季度日期的代码
-
获取本周第一天/最后一天、本月第一天/最后一天的时间戳
-
PHP获取今日、昨日、本周、上周、本月、上月、本季、上季、今年、去年
-
Asp.net C# 获取本周上周本月上月本年上年第一天最后一天时间大全
-
SQL获取本周,上周,本月,上月的开始时间和结束时间
-
JS获取今天是本月第几周、本月共几周、本月有多少天、是今年的第几周、是今年的第几天的示例代码
-
获取昨天、今天、上周、本周、本季度、本月、上月的开始日期、结束日期