Steve L
Steve L

Reputation: 1635

.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

Upvotes: 3

Views: 352

Answers (1)

DavidG
DavidG

Reputation: 118937

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";

Upvotes: 3

Related Questions