Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force DateTime variable to display only the Date without converting ToString()

Tags:

c#

datetime

wpf

I've got an object property, DateTime Date. I'm trying to keep this as a DateTime object, but display ONLY the date, i.e. 9/30/2013. I do not want to use a ToString() or ToShortDateString(). I have tried using Date.Date, but this still shows the date and time. Is there any way to view the date of a DateTime without converting it to a string?

I've also read this question. The question is worded the way I'd like, but the answers still use a ToShortDateString().

This will be displayed in a DataGrid that is bound to my object.

like image 457
PiousVenom Avatar asked Oct 26 '25 20:10

PiousVenom


1 Answers

A DateTime, by definition, will always have values for the date and the time. You can convert it to another DateTime representing the date portion (with a time of Midnight) via DateTime.Date.

However, in order to display the DateTime in a control, it will always be converted to a string. The best option is typically to try to control how that conversion occurs in your DataGrid:

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding TheDate, StringFormat={}{0:MM/dd/yyyy}}" />
    </DataGrid.Columns>
</DataGrid>

This will cause the column bound to "TheDate" to use a custom string format when displaying your DateTime.

like image 110
Reed Copsey Avatar answered Oct 28 '25 11:10

Reed Copsey