首页 前端知识 js 获取当前年月,通过 Date 对象来获取当前的年和年月 (格式:YYYY-MM)

js 获取当前年月,通过 Date 对象来获取当前的年和年月 (格式:YYYY-MM)

2025-03-20 12:03:33 前端知识 前端哥 187 599 我要收藏

在 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 形式或其他格式。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/24154.html
标签
评论
发布的文章

prompt工程起步

2025-03-23 11:03:21

ChatPromptTemplate的使用

2025-03-23 11:03:20

地基Prompt提示常用方式

2025-03-23 11:03:20

网络安全知识点

2025-03-23 11:03:15

第27周JavaSpringboot git初识

2025-03-23 11:03:15

Android studio运行报错处理

2025-03-23 11:03:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
浏览器升级提示:您的浏览器版本较低,建议您立即升级为知了极速浏览器,极速、安全、简约,上网速度更快!立即下载
复制成功!