0
点赞
收藏
分享

微信扫一扫

[js] 得到本月、上月、下月的起始、结束日期; 得到今年、去年、明年的开始、结束日期 day.js


方法一 自己写

// 格式化日期:yyyy-MM-dd
function formatDate(date) {
const year = date.getFullYear();
let month = date.getMonth() + 1;
let weekday = date.getDate();

if (month < 10) {
month = `0${month}`;
}
if (weekday < 10) {
weekday = `0${weekday}`;
}
return (`${year}-${month}-${weekday}`);
}

/**
* @description 得到本月、上月、下月的起始、结束日期
* @param {String} type 有两种选择,"s"代表开始,"e"代表结束
* @param {Number} months 不传或0代表本月,-1代表上月,1代表下月
*/
export function getMonth(type) {
const now = new Date(); // 当前日期
let nowYear = now.getYear(); // 当前年
const nowMonth = now.getMonth(); // 当前月
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;
}

/**
* @description 得到今年、去年、明年的开始、结束日期
* @param {String} type 有两种选择,"s"代表开始,"e"代表结束
* @param {Number} dates 不传或0代表今年,-1代表去年,1代表明年
*/
export function getYear(type, dates) {
const dd = new Date();
const n = dates || 0;
const year = dd.getFullYear() + Number(n);
let day;
if (type === 's') {
day = `${year}-01-01`;
}
if (type === 'e') {
day = `${year}-12-31`;
}
if (!type) {
day = `${year}-01-01/${year}-12-31`;
}
return day;
}

方法二 day.js

​​https://dayjs.fenxianglu.cn/category/​​

npm install dayjs --save

main.js

import dayjs from 'dayjs';
Vue.prototype.$dayjs = dayjs;

本月起始日期

dayjs().startOf('month').format('YYYY-MM-DD'); // 2022-08-01

本月结束日期

dayjs().endOf('month').format('YYYY-MM-DD'); // '2022-08-31'

​​开始时间​​​​显示​​

上月起始日期

dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD'); // 2022-07-01

上月结束日期

dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD'); // 2022-07-31

​​减少​​

下月起始日期

dayjs().add(1, 'month').startOf('month').format('YYYY-MM-DD'); // 2022-07-01

下月结束日期

dayjs().add(1, 'month').endOf('month').format('YYYY-MM-DD'); // 2022-07-31

​​增加​​


举报

相关推荐

0 条评论