Search code examples
c#.netwinformsdatetimepicker

Winforms .net Datepicker does not respect 24 hour format?


I have a timepicker (datetimepicker) formatted as HH:mm - 24 hour clock. It displays as 00 to 24 and 00 to 59 and will not allow invalid values to be entered. This is exactly what I want.

However, it returns values as 12 hours with AM and PM indicators. This means that when the user enters "00" it is returned as "12", and "14" is returned as "2:00". This is NOT what I want.

I can test for and convert these unwanted return values, but surely(?) there is a more elegant way of persuading this thing to give me the values I want rather than checking for these special conditions? Some simple property that I've overlooked perhaps?


Solution

  • When you read the value, you'll need to use:

    string value = dateTimePicker.Value.ToString("HH:mm");
    

    If you just use Value.ToString(), you'll get the default (12 hour) string formatting.