简体   繁体   中英

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!

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

Try this:

dateTimePicker1.Value = DateTime.Now.Date;

Doing that, hours, minutes and seconds will be set to 00:00:00.

type of dateTimePicker1.Value is DateTime. So try something like this:

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

You can try

dateTimePicker1.Value = DateTime.Now.Date;

This will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM