js实现年月
获取当前年月
使用JavaScript的Date对象可以轻松获取当前的年份和月份。Date对象提供了多种方法来获取日期和时间的不同部分。
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1; // 月份从0开始,需要加1
console.log(`当前年月: ${year}-${month}`);
格式化年月为YYYY-MM
为了确保月份始终是两位数,可以使用字符串的padStart方法进行格式化。这对于显示或存储日期时特别有用。

const formattedMonth = month.toString().padStart(2, '0');
console.log(`格式化后的年月: ${year}-${formattedMonth}`);
获取指定日期的年月
如果需要获取特定日期的年月,可以通过在创建Date对象时传入日期字符串或时间戳来实现。
const specificDate = new Date('2023-05-15');
const specificYear = specificDate.getFullYear();
const specificMonth = specificDate.getMonth() + 1;
console.log(`指定日期的年月: ${specificYear}-${specificMonth}`);
处理不同时区的年月
在处理跨时区的日期时,建议使用UTC方法来避免时区差异带来的问题。UTC方法返回的是世界标准时间下的日期部分。

const utcYear = currentDate.getUTCFullYear();
const utcMonth = currentDate.getUTCMonth() + 1;
console.log(`UTC年月: ${utcYear}-${utcMonth}`);
使用第三方库处理年月
对于更复杂的日期操作,可以使用第三方库如date-fns或moment.js。这些库提供了丰富的日期处理功能,简化了日期格式化和计算。
// 使用date-fns
import { format } from 'date-fns';
const formattedDate = format(new Date(), 'yyyy-MM');
console.log(`date-fns格式化年月: ${formattedDate}`);
// 使用moment.js
const momentDate = moment().format('YYYY-MM');
console.log(`moment.js格式化年月: ${momentDate}`);
计算未来或过去的年月
通过调整Date对象的值,可以计算未来或过去的年月。这对于生成日期范围或进行日期推算非常有用。
const futureDate = new Date();
futureDate.setMonth(futureDate.getMonth() + 3); // 三个月后
console.log(`三个月后的年月: ${futureDate.getFullYear()}-${futureDate.getMonth() + 1}`);
const pastDate = new Date();
pastDate.setMonth(pastDate.getMonth() - 2); // 两个月前
console.log(`两个月前的年月: ${pastDate.getFullYear()}-${pastDate.getMonth() + 1}`);






