WPF Datepicker - SelectedDate just date and not time

28,391

Solution 1

DatePicker.SelectedDate.Value.Date is a DateTime Nullable property. So any DateTime Property has the date and time section. but in this case it is not fill with the correct value and it will gives you the default value. if you want to get the date only use following code,

DatePicker.SelectedDate.Value.Date.ToShortDateString()

Solution 2

SelectedDate property is of type Nullable<DateTime> it gives you the date however the time is reset as 12:00:00 midnight (00:00:00)

see more on DatePicker.SelectedDate Property

from MSDN: DateTime.Date Property

The value of the Kind property of the returned DateTime value is the same as that of the current instance. Because the DateTime type represents both dates and times in a single type, it is important to avoid misinterpreting a date returned by the Date property as a date and time. For more information, see "Saving and Restoring DateTime Values" in the DateTime topic.

Solution 3

While selecting the date from the datepicker in you code you can do following:

    DateTime from = From_Date_Picker.SelectedDate.Value.Date

Solution 4

The following example uses the Date property to extract the date component of a DateTime value with its time component set to zero (or 0:00:00, or midnight). It also illustrates that, depending on the format string used when displaying the DateTime value, the time component can continue to appear in formatted output.

That says that depending on the Format (in this case the DatePicker i think) the Time component can appear. Like in your link, the Output is 12:00 AM

So Check the Format / properties of the DatePicker.

Solution 5

in your code, you can do the following:

string shortDate = datePicker.SelectedDate.Value.ToShortDateString();

or, if you'd like to specify the format of the date:

string formatDate = datePicker.SelectedDate.Value.ToString("yyyy-MM-dd");

Here datePicker is object of DatePicker WPF

Share:
28,391
user3428422
Author by

user3428422

.NET till I die.

Updated on March 31, 2021

Comments

  • user3428422
    user3428422 about 3 years

    I know this may be a duplicate but using the .NET framework I cant seem to get the date and not the time for a WPF DatePicker

    I have this

    DatePicker.SelectedDate.Value.Date <--- I believed using the "Date" property would only return the date, but it returns the time "12:00:00" as well. 
    

    I read this http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx so I not sure what I am doing wrong.

    Am sure its something silly as always. But with no helpful eye with me to tell me, I thought I resort to SO!

    Thanks