首页 文章

如何使日期时间选择器始终包含该月的最后一天,同时仅显示月份和年份?

提问于
浏览
6

我有一个DateTimePicker,我设置为只显示月份和年份,如下所示:

myDateTimePicker.Format = DateTimePickerFormat.Custom;
myDateTimePicker.CustomFormat = "MMMM yyyy";
myDateTimePicker.ShowUpDown = true;

但是,我希望日期的值始终是所选月份的最后一天,因此我使用以下方法在ValueChanged事件中设置DateTime:

DateTime selectedDate = myDateTimePicker.Value;
DateTime lastDayOfMonth = new DateTime(
    selectedDate.Year,
    selectedDate.Month,
    DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month));
myDateTimePicker.Value = lastDayOfMonth;

问题是,如果我选择了像March这样的月份,并且使用向上/向下控件将月份更改为2月,则在处理ValueChanged事件之前会出现以下错误:

ArgumentOutOfRangeException was unhandled
Year, Month, and Day parameters describe an un-representable DateTime.

这是可以理解的,因为日期是3月31日,并且它被更改为2月31日,这是无效日期 . 但是,我想将其更改为2月28日(或2月29日) .

我怎样才能做到这一点?

2 回答

  • 4

    很奇怪,我试图重现你的问题,当我从3月切换到2月时,我的控件只是没有显示任何东西......也许我们有不同的框架版本,他们以不同的方式处理相同的错误 .

    无论如何,一个解决方案是将日期时间选择器设置为每个月的第一个,当您需要该值时,您可以只使用当前的代码:

    DateTime lastDayOfMonth = new DateTime(
        selectedDate.Year, 
        selectedDate.Month, 
        DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month));
    

    由于您从不使用数据时间选择器的日期值,因此您可以将其设置为1,这将始终提供现有日期 .

    这个解决方案让我感觉不舒服,因为你使用的日期与你从控件获得的日期不同 - 总是可能的错误来源,IMO . 记得在你的代码中添加注释,解释你为什么这样做;-)

  • 2

    我可能会像Treb Selected那样使用本月的第一天,但是扩展DateTimePicker以便在执行此操作时:

    MyDateTimePicker.Value

    它会做这样的事情:

    get{
    return value.addMonths(1).addDays(-1)
    }
    

相关问题