自己准备写一个日期选择器,数据上经常需要获得本月、下月、前3月、后3月等。
为了方便,自己写了一个函数,函数接受一个参数(偏移offset,默认为0),用于进行月偏移。
例如当前年月是2022-5,调研结果示例:
[JavaScript] 纯文本查看 复制代码 console.log('去年本月:', method.getYearMonth(-12))
console.log('半年前:', method.getYearMonth(-6))
console.log('上月:', method.getYearMonth(-1))
console.log('本月:', method.getYearMonth())
console.log('下月:', method.getYearMonth(1))
console.log('半年后:', method.getYearMonth(6))
console.log('明年本月:', method.getYearMonth(12))
函数代码:
[JavaScript] 纯文本查看 复制代码 const method = {
getYearMonth: (offset = 0) => {
// 获得当前年月
const date = new Date(),
y = date.getFullYear(),
m = date.getMonth() + 1;
// 获得偏移年月
const year = Math.floor((y * 12 + m + offset) / 12.000000000000001),
month = (y * 12 + m + offset) % 12 || 12;
// 返回
return [year, month]
}
};
console.log(method.getYearMonth(-12000))
console.log('👆前1千年👆')
console.log(method.getYearMonth(-10))
console.log(method.getYearMonth(-9))
console.log(method.getYearMonth(-8))
console.log(method.getYearMonth(-7))
console.log(method.getYearMonth(-6))
console.log(method.getYearMonth(-5))
console.log(method.getYearMonth(-4))
console.log(method.getYearMonth(-3))
console.log(method.getYearMonth(-2))
console.log(method.getYearMonth(-1))
console.log('👆前10个月👆')
console.log('当前月:', method.getYearMonth())
console.log('👇后10个月👇')
console.log(method.getYearMonth(1))
console.log(method.getYearMonth(2))
console.log(method.getYearMonth(3))
console.log(method.getYearMonth(4))
console.log(method.getYearMonth(5))
console.log(method.getYearMonth(6))
console.log(method.getYearMonth(7))
console.log(method.getYearMonth(8))
console.log(method.getYearMonth(9))
console.log(method.getYearMonth(10))
console.log('👇后1千年👇')
console.log(method.getYearMonth(12000))
以上,欢迎各位大佬讨论、优化,谢谢。 |