Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a dateTimePicker value to DateTime.MaxValue

Tags:

c#

This generates an error at runtime:

dateTimePicker.Value = DateTime.MaxValue;
like image 764
programmernovice Avatar asked Oct 25 '09 13:10

programmernovice


People also ask

What is the value of DateTime Maxvalue?

Remarks. The value of this constant is equivalent to 23:59:59.9999999 UTC, December 31, 9999 in the Gregorian calendar, exactly one 100-nanosecond tick before 00:00:00 UTC, January 1, 10000.

What is DateTime Maxvalue in C#?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.

What is DateTimePicker C#?

The DateTimePicker control allows you to display and collect date and time from the user with a specified format. The DateTimePicker control has two parts, a label that displays the selected date and a popup calendar that allows users to select a new date.


3 Answers

You can't.

The maximum date supported by DateTimePicker is DateTimePicker.MaximumDateTime, which is 12/31/9998; DateTime.MaxValue is 12/31/9999 23:59:59, which is one year and one day later.

Can you use that DateTimePicker.MaximumDateTime instead of DateTime.MaxValue?

like image 124
SLaks Avatar answered Oct 24 '22 02:10

SLaks


You need to use the DateTimePicker.MaximumDateTime property. The maximum value allowable for the datetime picker is 31/12/9998, as represented by DateTimePicker.MaximumDateTime. Whereas the value of DateTime.MaxValue is 31/12/9999.

like image 45
Phaedrus Avatar answered Oct 24 '22 01:10

Phaedrus


Yes you can, but it is quite dirty (use it at your own risk). Basically, it overwrites the MaxValue defined in the DateTimePicker with the MaxValue from the DateTime object.

Paste this code into the Main (or any method run during startup):

var dtpType = typeof(DateTimePicker);
var field = dtpType.GetField("MaxDateTime", BindingFlags.Public | BindingFlags.Static);
if (field != null)
{
    field.SetValue(new DateTimePicker(), DateTime.MaxValue);
}
like image 2
Johann Blais Avatar answered Oct 24 '22 01:10

Johann Blais