在JavaScript中生成当前的年月可以使用Date
对象。以下是一个简单的示例代码:
// 创建一个新的Date对象,默认为当前日期和时间
const now = new Date();
// 获取年份(四位数)
const year = now.getFullYear();
// 获取月份(0-11),所以需要加1
const month = now.getMonth() + 1;
// 将年份和月份拼接成字符串,例如 "2023-04"
const currentYearMonth = `${year}-${month.toString().padStart(2, '0')}`;
console.log(currentYearMonth); // 输出当前年月,例如 "2023-04"
Date
对象用于处理日期和时间。Date
对象提供了丰富的方法来处理日期和时间。getMonth()
方法返回的是0-11,所以需要加1。padStart()
方法确保月份始终是两位数。通过上述方法,你可以轻松地在JavaScript中生成当前的年月,并根据需要进行格式化和应用。
领取专属 10元无门槛券
手把手带您无忧上云