在 JavaScript 中可以通过 Date
对象来获取当前的年和年月:
1. 获取当前年
const currentYear = new Date().getFullYear(); console.log(currentYear); // 例如:2024
复制
2. 获取当前年月(格式:YYYY-MM)
const date = new Date(); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以要 +1 const currentYearMonth = `${year}-${month}`; console.log(currentYearMonth); // 例如:2024-10
复制
解释:
getFullYear()
:获取当前的完整年份(如 2024)。getMonth()
:获取当前月份(0 表示 1 月,11 表示 12 月),所以我们需要 +1。padStart(2, '0')
:保证月份是两位数格式,比如 1 月会变成01
。
你可以根据需求自定义格式,比如获取 YYYY/MM
形式或其他格式。