How to set datetimepicker value for date only in (.NET)

I have a DateTimePicker in my form, and I set the value for the custom format property “dd / MM / yyyy” ant when I run this code:

MessageBox.Show(dateTimePicker1.Value.ToString());

I get this value: 03/26/2010 1:26.

How can I remove part of the time from a value.

I know that we can use this method

 dateTimePicker1.Value.ToShortDateString(); 

but I want to set the value property to this format "dd / MM / yyyy" , so the output will be like this "26/3/2010" , because I want to store the value in my database (SQL)

How can i do this?

+6
c #
source share
4 answers

Use dateTimePicker1.Value.Date to get the Date part of this DateTime value.

Note that if you want to parse strings, using dateTimePicker1.Value.Date.ToString will result in the string "03/26/2010 00:00:00", while using something like MyString = CStr(dateTimePicker1.Value.Date) will cause MyString to be "03/26/2010".

+12
source share

I assume that you initialized DateTimePicker with the current date and time:

 dateTimePicker1.Value = DateTime.Now; 

Instead, initialize it with the current date:

 dateTimePicker1.Value = DateTime.Today; 

What's happening:

  • If the user selects a date, the DateTimePicker.Value property will always return the date without the time component of the day, and DateTime.Kind be Unspecified .

  • If the user does not select a date, the DateTimePicker.Value property returns the value used to initialize the DateTimePicker.Value property. If you initialize it using DateTime.Now , it will have a time of day component, and DateTime.Kind will be set to Local .

+4
source share

just MessageBox.Show(dateTimePicker1.Value.ToString("dd/MM/yyyy"));

+1
source share

If you have a string as the data type in the database:

  dateTimePicker1.Value.Date.ToString("d"); 

If the data type is DateTime:

  dateTimePicker1.Value.Date; 

Both return a date in the format dd / mm / yyyy without time.

0
source share

All Articles