// 获取当前的年份和月份
function getYearMonth() {
// 创建一个新的 Date 对象,表示当前日期和时间
const now = new Date();
// 获取年份,getFullYear() 方法返回四位数的年份
const year = now.getFullYear();
// 获取月份,getMonth() 方法返回的是 0-11 的整数,需要加 1 转换为 1-12
const month = now.getMonth() + 1;
// 返回一个包含年份和月份的对象
return {
year: year,
month: month
};
}
// 示例调用
const result = getYearMonth();
console.log(`当前年份: ${result.year}, 当前月份: ${result.month}`);
这段代码定义了一个 getYearMonth
函数,用于获取当前的年份和月份。它使用了 JavaScript 的 Date
对象来获取当前日期,并通过 getFullYear()
和 getMonth()
方法分别获取年份和月份。由于 getMonth()
返回的月份是从 0 开始的(即 0 表示 1 月),因此需要加 1 进行修正。最后,函数返回一个包含年份和月份的对象。
上一篇:js 获取星期几
下一篇:js string slice
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站