Search code examples
c#datetimepickercustom-properties

Reading & displaying value in Datetimepicker


I am writing a date in xml file & then reading a date from xml file to display. I have used Datetimepicker which has customFormat= MM/dd/yyyy. & it sets <date>02/29/2001</date> in xmlfile.

while reading if value is "02/02/2001"it reads & shows it perfectly in datetimepicker

but if value is "02/22/2001". edited:

it throws an exception.
String was not recognized as a valid DateTime.


Solution

  • Have you set the cultureinfo of your application to expect the date in a MM/dd/yyyy format? It seems like it is expecting dd/MM/yyyy, that's why 02/02/2001 works, I suspect 28/02/2001 would work as well.

    Edit: Hang on, 2001 was not a leap year, 29/02/2001 will never be a valid date!

    Edit: added sample

    // C#
    // Put the using statements at the beginning of the code module
    using System.Threading;
    using System.Globalization;
    // Put the following code before InitializeComponent()
    // Sets the culture to English (US)
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    // Sets the UI culture to English (US)
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
    

    from here: http://msdn.microsoft.com/en-us/library/b28bx3bh%28v=vs.80%29.aspx more info in the link to the class in the comments