当前位置:首页 > 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实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现tab选项卡切换

js实现tab选项卡切换

实现Tab选项卡切换的JavaScript方法 使用纯JavaScript实现Tab切换功能,可以通过监听点击事件动态切换内容显示状态。以下是两种常见实现方式: 基础DOM操作实现 // 获取所有…

js实现排序

js实现排序

数组排序方法 JavaScript提供了内置的sort()方法用于数组排序。默认情况下,sort()将元素转换为字符串并按照Unicode码点排序。对于数字排序,需传入比较函数。 const num…

js实现乘法

js实现乘法

实现乘法运算的方法 在JavaScript中实现乘法运算可以通过多种方式完成,以下列举几种常见方法: 基础运算符 直接使用乘法运算符*是最简单的方式: let result = 3 * 5; //…