在JavaScript中生成12个月起止日期并插入GridView的问题
基于起始日期生成12个月月度起止日期并添加到GridView
我有一个名为gvFiscalPeriod的GridView,还有一个供用户输入起始日期(例如1/11/2022)的文本框。需要基于该日期生成未来12个月的每月起止日期,每行对应一个月份,示例如下:
| id | StartDate | EndDate |
|---|---|---|
| 1 | 1/11/2022 | 30/11/2022 |
| 2 | 1/12/2022 | 31/12/2022 |
| 3 | 1/1/2023 | 31/01/2023 |
现有实现代码
Razor视图代码
<table id="gvFiscalPeriod" class="display nowrap table table-hover table-bordered" style="width:100%;cursor:pointer;display:none"> @{ <thead> <tr> <th>ID</th> <th class="th-label-vertical-align">From Date</th> <th class="th-label-vertical-align">To Date</th> </tr> </thead> <tbody> @{ int i = 0; colArray = new string[] { "ID","FromDate", "ToDate"}; foreach (var item in Model.PeriodList) { _colCount = 0; foreach (var colName in colArray) { if (_colCount == 0) {@:<tr> } if (chkColExist(item, colName.Replace(" ", ""))) { var colProperty = item.GetType().GetProperty(colName.Replace(" ", "")); if (colProperty != null) { dynamic colValue = colProperty.GetValue(item, null); if (colProperty.Name.ToString() == "FromDate" || colProperty.Name.ToString() == "ToDate") { colValue = colValue.ToString(Model.GlobalFormatDateList[0].Value); } else if (colName == "ID") { <td id="chk-ID-@i"> @Html.Raw(colValue) </td> } else { <td> @Html.Raw(colValue) </td> } _colCount++; } } if (_colCount == colArray.Length) {@:</tr> } } i++; } gvColumnLength = colArray.Length.ToString(); } </tbody> } </table>
JavaScript代码
function SaveAddFiscalPeriod() { gvDT.row.add([ ID, $(StartDate).val(), $(EndDate).val() ]).draw(false); gvDT.columns.adjust().draw(); } });
当前问题:上述脚本仅能添加一行,需要实现添加12行对应12个月起止日期的功能。
解决方案
修改SaveAddFiscalPeriod函数,通过循环计算每个月的起止日期并批量添加到表格:
修改后的JavaScript代码
function SaveAddFiscalPeriod() { // 获取用户输入的起始日期,转为Date对象 let inputStartDate = new Date($('#StartDate').val()); // 循环生成12个月的数据 for (let index = 0; index < 12; index++) { // 计算当前月份的第一天 let currentMonthStart = new Date(inputStartDate.getFullYear(), inputStartDate.getMonth() + index, 1); // 计算当前月份的最后一天:下一个月第一天的前一天 let currentMonthEnd = new Date(inputStartDate.getFullYear(), inputStartDate.getMonth() + index + 1, 0); // 格式化日期为dd/mm/yyyy格式(匹配示例格式) let formattedStart = `${currentMonthStart.getDate()}/${(currentMonthStart.getMonth() + 1).toString().padStart(2, '0')}/${currentMonthStart.getFullYear()}`; let formattedEnd = `${currentMonthEnd.getDate()}/${(currentMonthEnd.getMonth() + 1).toString().padStart(2, '0')}/${currentMonthEnd.getFullYear()}`; // 添加行到DataTable,ID为循环索引+1 gvDT.row.add([ index + 1, formattedStart, formattedEnd ]).draw(false); } gvDT.columns.adjust().draw(); }
核心说明
- 日期计算逻辑:利用
Date对象的特性,传入年份、月份(注意月份从0开始计数)和日期参数,直接获取当月第一天和下月第一天,再将下月第一天减一天得到当月最后一天。 - 日期格式化:用
padStart(2, '0')确保月份和日期始终为两位数字,避免出现1/1/2023这类格式不一致的情况。 - 批量添加:通过12次循环,每次计算对应月份的起止日期并调用
row.add()添加行,最后统一调整列宽并刷新表格。
可选调整
- 如果需要保留表格原有数据,无需添加清空逻辑;若要覆盖原有数据,可在循环前添加
gvDT.clear().draw()。 - 若用户输入的日期格式存在解析问题,可引入日期处理库(如moment.js)简化格式转换操作。
内容的提问来源于stack exchange,提问作者Durga Valli
相关产品推荐
相关产品推荐

