You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ExtJS新手求助:基于指定月份和年份获取该月首尾日期

如何根据指定月份名称和年份获取第一天和最后一天(ExtJS/JS)

已知具体月份名称(如'March')和年份(如2023)时,核心思路是先将月份名称转换为Date构造函数需要的0-11数字索引,再复用你已经掌握的日期计算逻辑。

实现代码

// 定义完整的月份名称数组,索引对应0-11(JS中月份从0开始计数)
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 
                    'July', 'August', 'September', 'October', 'November', 'December'];

// 你的目标月份和年份
const targetMonth = 'March';
const targetYear = 2023;

// 将月份名称转为对应数字索引
const monthIndex = monthNames.indexOf(targetMonth);

// 计算该月第一天
const firstDay = new Date(targetYear, monthIndex, 1);
// 计算该月最后一天:传入下一个月份+0,会自动回退到当前月最后一天
const lastDay = new Date(targetYear, monthIndex + 1, 0);

// 若使用ExtJS,可格式化输出(可选)
console.log('第一天:', Ext.Date.format(firstDay, 'Y-m-d'));
console.log('最后一天:', Ext.Date.format(lastDay, 'Y-m-d'));

注意事项

  • 如果你的月份名称存在大小写不一致的情况(比如'march'或'MARCH'),可以先统一格式再匹配:
    const normalizedMonth = targetMonth.charAt(0).toUpperCase() + targetMonth.slice(1).toLowerCase();
    const monthIndex = monthNames.indexOf(normalizedMonth);
    
  • 确保月份名称拼写正确,否则indexOf会返回-1,此时需要添加异常处理逻辑。

内容的提问来源于stack exchange,提问作者Nag Raju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 23:02:41