C# 的winform中有两个dateTimePicker 默认值一个设置为本月月初,一个设置为本月月末,该怎么设置呢,谢谢

2025-06-26 15:34:35
推荐回答(3个)
回答1:

前一个好办,dateTimePicker1.Value=new DateTime(DateTime.Now.Year,DateTime.Now.Month,1);
后一个有点麻烦,加一个月减去已过去的天数:
idateTimePicker2.Value=DateTime.Now.Date.AddMonths(1).AddDays(-DateTime.Now.Day);

回答2:

datetimepicker1.value=DateTime.Now.AddDay(1-DateTime.Now.Day); //月初
datetimepicker2.value=DateTime.Now.AddMonth(1).AddDay(1-DateTime.Now.Day); //月末

好像记得是这样写的,大概就这样吧

回答3:

步骤:
1.获取当前日期,并得到当前年份、月份
2.计算当前月份总天数(switch月份,注意判断是否是闰年),并根据天数确定本月最后一天的日期28/29/30/31
3.用步骤1取得的年份月份构建两个dateTime。(年/月/1)。(年/月/最后一天)

源码:
private void button1_Click(object sender, EventArgs e)
{
DateTime DTN = DateTime.Now.Date;
DateTime DT1 = new DateTime(DTN.Year, DTN.Month, 1);
DateTime DT2 = DateTime.Now.Date;
bool WrightDate = false;
try
{
if (!WrightDate)
{
DT2 = new DateTime(DTN.Year, DTN.Month, 31);
WrightDate = true;
}
}
catch { }
try
{
if (!WrightDate)
{
DT2 = new DateTime(DTN.Year, DTN.Month, 30);
WrightDate = true;
}
}
catch { }
try
{
if (!WrightDate)
{
DT2 = new DateTime(DTN.Year, DTN.Month, 29);
WrightDate = true;
}
}
catch { }
try
{
if (!WrightDate)
{
DT2 = new DateTime(DTN.Year, DTN.Month, 28);
WrightDate = true;
}
}
catch { }
dateTimePicker1.Value = DT1;
dateTimePicker2.Value = DT2;
}