/**
* 获取当前日期,返回格式:YYYY-MM-DD
*/
const getCurrentDate = (): any => {
return new Date()
.toLocaleDateString()
.split("/")
.map(item => {
if (parseInt(item) < 10) {
return "0" + item;
} else {
return item;
}
})
.join("-");
};
/**
* 获取当前月
* @returns 返回格式:YYYYMM
*/
function getNowMonth() {
const date = new Date();
const year: number | string = date.getFullYear(); //当前年:四位数字
let month: number | string = date.getMonth() + 1; //当前月:1-12
month = month < 10 ? "0" + month : month; //月份格式化:月份小于10则追加个0
const lastMonth = year + "" + month;
return lastMonth;
}
/**
* 获取上个月
* @returns 返回格式:YYYYMM
*/
function getLastMonth() {
const date = new Date();
let year: number | string = date.getFullYear(); //当前年:四位数字
let month: number | string = date.getMonth(); //当前月:0-11
if (month == 0) {
//如果是0,则说明是1月份,上一个月就是去年的12月
year -= 1;
month = 12;
}
month = month < 10 ? "0" + month : month; //月份格式化:月份小于10则追加个0
const lastMonth = year + "" + month;
return lastMonth;
}
export { getCurrentDate, getLastMonth, getNowMonth };
前端常用方法 获取当前日期 当月 上个月
最新推荐文章于 2024-04-15 07:13:03 发布