js获取上月开始和结束时间
/**
时间格式化
*/
function formatDate(val) {
var date = new Date(Number(val)); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + "-";
var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
var D = date.getDate() + " ";
var h = date.getHours() + ":";
var m = date.getMinutes() + ":";
var s = (date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds());
return Y + M + D + h + m + s;
}
/**
* @description 得到本月、上月、下月的起始、结束日期
* @param {String} type 有两种选择,"s"代表开始,"e"代表结束
* @param {Number} months 不传或0代表本月,-1代表上月,1代表下月
*/
function getMonth(type,months = 0) {
const now = new Date(); // 当前日期
let nowYear = now.getYear();
const nowMonth = now.getMonth() - months;
nowYear += (nowYear < 2000) ? 1900 : 0; let result;
if (type === 's') {
const monthStartDate = new Date(nowYear, nowMonth, 1);
result = formatDate(monthStartDate);
} else {
const monthStartDate = new Date(nowYear, nowMonth, 1);
const monthEndDate = new Date(nowYear, nowMonth + 1, 1);
const days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
result = formatDate(new Date(nowYear, nowMonth, days));
}
return result;
}
然后在需要本月或上月开始或结束时间的地方使用 getMonth
函数即可。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论此文章
已有0人参与了评论