Search code examples
c#datetimepicker

How to set the time in date timepickers in c#


I'm new to date timepickers. I was wondering if someone could explain them to me properly. I have a booking system that you must be able to book a date and specific time in the future and reserve that time frame in a sql database. Can I do it with date timepickers? It has a nice interface when its on my form but I cant see a way for the user to set the time? it always just gives me the default time. Any help? thanks

https://i.sstatic.net/M1CbU.jpg


Solution

  • The DateTimePicker-Control has a Format-Property, which will set the format of the date and time displayed in the control. AS stated in this answer you can use following format to show Date and time:

    dateTimePicker1.Format = DateTimePickerFormat.Custom;
    dateTimePicker1.CustomFormat = "MM.dd.yyyy hh:mm:ss";
    

    Here you can get a list of all format string and their descriptions: List of CustomFormat-String

    The result will look like this:

    DateTimePicker Custom Format

    .NET also has a structure called DateTime to save your selected value. You can save it with following code

    DateTime yourSelectedDateTime  = dateTimePicker1.Value;
    textBox1.Text = yourSelectedDateTime.ToString();