Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET System.Windows.Forms DateTimePicker CustomFormat incorrect

Here's the code:

   DateTime dt = new DateTime( 2016, 8, 3);
   dtpStart.Format = DateTimePickerFormat.Custom;
   dtpStart.CustomFormat = "Mdyyyy"; //format;
   dtpStart.Value = dt;
   string s = String.Format( "{0:Mdyyyy}", dt );
   System.Console.Write( s );

In the DateTimePicker (dtpStart) I see " 8 32016", which has the month and day each left-padded with a space, while the console output shows the expected value "832016".

The problem is that we're seeing this unexpected padding of the month and day, regardless of the format we supply, e.g.:

Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern

like image 852
Steve L Avatar asked May 08 '26 07:05

Steve L


1 Answers

The DateTimePicker control is trying to be helpful and let you enter a date manually with the keyboard instead of the dropdown. If the numbers were displayed without spaces the date would be ambiguous. For example, what date does this refer to:

1232016

Is it December 3, 2016 or January 23, 2016? So the spaces are required. Your best bet is to give the day and month values a leading zero:

dtpStart.CustomFormat = "MMddyyyy";
like image 189
DavidG Avatar answered May 09 '26 19:05

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!