Search code examples
c#timesetdatetimepicker

c# datetimepicker set time


On my WinForm, I want a user to be able to 'reset' or 'clear' the datetimepicker on a buttonclick. My goal is to set it to 00:00 AM, but am unable to do so.

I've tried:

dateTimePicker1.Value = ("00:00: AM");

int reset = int.Parse("00:00: AM");

dateTimePicker1.Value = reset;

The datetimepicker is in a custom format: hh:mm:tt

Any help is appreciated!


Solution

  • Try changing your custom format from hh:mm tt to HH:mm tt.

    dateTimePicker1.Format = DateTimePickerFormat.Custom;
    dateTimePicker1.CustomFormat = "HH:mm tt";
    dateTimePicker1.Value = DateTime.Now.Date;
    

    As we can see at MSDN
    https://msdn.microsoft.com/EN-US/library/8kb3ddd4%28v=VS.110,d=hv.2%29.aspx:
    "hh" - The hour, using a 12-hour clock from 01 to 12.
    "HH" - The hour, using a 24-hour clock from 00 to 23.

    So, we can expect the following behavior:

    DateTime date = new DateTime(2015, 02, 19, 0, 0, 0);
    Console.WriteLine(date.ToString("hh:mm tt", CultureInfo.InvariantCulture));
    // Displays 12:00 AM
    Console.WriteLine(date.ToString("HH:mm tt", CultureInfo.InvariantCulture));
    // Displays 00:00 AM