js实现年月
获取当前年月
使用 Date 对象可以轻松获取当前的年份和月份。
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1; // 月份从0开始,需加1
console.log(`${year}-${month.toString().padStart(2, '0')}`);
格式化年月为 YYYY-MM
确保月份始终为两位数,不足时补零。
function formatYearMonth(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
return `${year}-${month}`;
}
console.log(formatYearMonth(new Date()));
生成指定范围的年月列表
生成从某年到当前年月或指定范围的年月数组。

function generateYearMonthList(startYear, endYear = new Date().getFullYear()) {
const list = [];
for (let year = startYear; year <= endYear; year++) {
for (let month = 1; month <= 12; month++) {
list.push(`${year}-${month.toString().padStart(2, '0')}`);
}
}
return list;
}
console.log(generateYearMonthList(2020, 2023));
解析年月字符串
将格式为 "YYYY-MM" 的字符串解析为年份和月份。
function parseYearMonth(yearMonthStr) {
const [year, month] = yearMonthStr.split('-').map(Number);
return { year, month };
}
console.log(parseYearMonth('2023-05'));
计算年月的增减
根据当前年月计算前几个月或后几个月。

function addMonths(yearMonthStr, monthsToAdd) {
const { year, month } = parseYearMonth(yearMonthStr);
const date = new Date(year, month - 1 + monthsToAdd);
return formatYearMonth(date);
}
console.log(addMonths('2023-05', 3)); // 输出 "2023-08"
console.log(addMonths('2023-05', -2)); // 输出 "2023-03"
比较两个年月
判断两个年月字符串的先后顺序。
function compareYearMonth(a, b) {
const dateA = new Date(a);
const dateB = new Date(b);
return dateA - dateB;
}
console.log(compareYearMonth('2023-05', '2023-08')); // 输出负数表示a早于b
获取某个月的天数
计算指定年月的总天数。
function getDaysInMonth(yearMonthStr) {
const { year, month } = parseYearMonth(yearMonthStr);
return new Date(year, month, 0).getDate();
}
console.log(getDaysInMonth('2023-02')); // 输出28或29(闰年)






