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

DateTimePicker选择2019年后日期存入DataGridView出现异常

日期格式化错误导致DataGridView日期显示异常的解决办法

我一眼就看出问题出在哪了——你在格式化日期的时候用错了格式符!

你看这段代码里的日期格式化部分:

POdataGrid["Production_Date", row].Value = POpDateDP.Value.ToString("dd/mm/yyyy");
POdataGrid["Expiry_Date", row].Value = POexpDateDP.Value.ToString("mm/dd/yyyy");

这里的小写mm代表的是分钟,不是月份!大写的MM才是用来表示月份的。这就导致你选的月份被错误替换成了DateTimePicker里的分钟值,进而出现月份显示错乱、年份看起来异常的问题。

只要把格式字符串里的小写mm换成大写MM就能解决问题,修正后的完整代码如下:

private void button36_Click(object sender, EventArgs e) {
    int row = 0;
    POdataGrid.Rows.Add();
    row = POdataGrid.Rows.Count - 2;
    POdataGrid["Product_Name",row].Value = POproductNameTB.Text;
    POdataGrid["Product_Type",row].Value = POproductTypeCB.Text;
    POdataGrid["Unit_Type",row].Value = POunitTypeCB.Text;
    POdataGrid["Unit_Price", row].Value = POunitPriceTB.Text;
    POdataGrid["Quantity",row].Value = POquantityTB.Text;
    POdataGrid["Total_Price",row].Value = POtotalPrice1TB.Text;
    POdataGrid["Bonus",row].Value = PObonusTB.Text;
    POdataGrid["Sell_Price",row].Value = POsellPriceTB.Text;
    POdataGrid["Interest", row].Value = POinterestTB.Text;
    // 将小写mm改为大写MM,正确表示月份
    POdataGrid["Production_Date", row].Value = POpDateDP.Value.ToString("dd/MM/yyyy");
    POdataGrid["Expiry_Date", row].Value = POexpDateDP.Value.ToString("MM/dd/yyyy");
}

再给你明确下几个常用日期格式符的区别:

  • mm:00-59,代表分钟
  • MM:01-12,代表月份
  • dd:01-31,代表日期
  • yyyy:4位数的年份

修改后,你选择的日期就能正确显示到DataGridView里,不会再出现月份错乱、年份异常的问题了。

内容的提问来源于stack exchange,提问作者Suhail Taleb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:46:25