当前位置:首页 > JavaScript

js实现年月

2026-03-15 20:08:11JavaScript

获取当前年月

使用 Date 对象可以轻松获取当前的年份和月份。

const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1; // 月份从0开始,需加1
console.log(`${year}-${month.toString().padStart(2, '0')}`);

格式化年月为 YYYY-MM

确保月份始终为两位数,不足时补零。

function formatYearMonth(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  return `${year}-${month}`;
}
console.log(formatYearMonth(new Date()));

生成指定范围的年月列表

生成从某年到当前年月或指定范围的年月数组。

js实现年月

function generateYearMonthList(startYear, endYear = new Date().getFullYear()) {
  const list = [];
  for (let year = startYear; year <= endYear; year++) {
    for (let month = 1; month <= 12; month++) {
      list.push(`${year}-${month.toString().padStart(2, '0')}`);
    }
  }
  return list;
}
console.log(generateYearMonthList(2020, 2023));

解析年月字符串

将格式为 "YYYY-MM" 的字符串解析为年份和月份。

function parseYearMonth(yearMonthStr) {
  const [year, month] = yearMonthStr.split('-').map(Number);
  return { year, month };
}
console.log(parseYearMonth('2023-05'));

计算年月的增减

根据当前年月计算前几个月或后几个月。

js实现年月

function addMonths(yearMonthStr, monthsToAdd) {
  const { year, month } = parseYearMonth(yearMonthStr);
  const date = new Date(year, month - 1 + monthsToAdd);
  return formatYearMonth(date);
}
console.log(addMonths('2023-05', 3)); // 输出 "2023-08"
console.log(addMonths('2023-05', -2)); // 输出 "2023-03"

比较两个年月

判断两个年月字符串的先后顺序。

function compareYearMonth(a, b) {
  const dateA = new Date(a);
  const dateB = new Date(b);
  return dateA - dateB;
}
console.log(compareYearMonth('2023-05', '2023-08')); // 输出负数表示a早于b

获取某个月的天数

计算指定年月的总天数。

function getDaysInMonth(yearMonthStr) {
  const { year, month } = parseYearMonth(yearMonthStr);
  return new Date(year, month, 0).getDate();
}
console.log(getDaysInMonth('2023-02')); // 输出28或29(闰年)

标签: 年月js
分享给朋友:

相关文章

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…

js实现点击显示和隐藏

js实现点击显示和隐藏

实现点击显示和隐藏的JavaScript方法 使用classList.toggle切换类名 通过添加/移除CSS类控制元素的显示与隐藏,需提前在CSS中定义隐藏样式(如display: none)。…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…