Reputation: 13574
Xaml code
<DatePicker Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="100,50,0,10" Name="dateText" VerticalAlignment="Top" Width="120" >
<DatePicker.SelectedDate>
<Binding Source="{StaticResource insertTransaction}" Path="Date" />
</DatePicker.SelectedDate>
</DatePicker>
he code for date property in the above binded(insertTransaction) class
private DateTime? date;
public DateTime? Date
{
get { return this.date; }
set { this.date = value; }
}
How can i retrieve just the date part and not the whole date and time. Nullable date is mandatory because user might not know the date at first time and may enter it later. DateTime.ToShortDateTime() doesn't work on DateTime?
Upvotes: 2
Views: 4745
Reputation: 834
Change your code to:
public DateTime? Date {
get { return this.date.Value.Date; }
set { this.date = value; }
}
You will also get time which is to be neglected and the dummy one (as 12:00AM something)
If you want exactly date without time, you have to accept it as string ToShortDateTime();
in get
.
Upvotes: 3
Reputation: 13574
Thanks all !! I guess i was heading south instead of north :-P .... Well Now i am going to use the Nullable DateTime? the way it's supposed to be used. Instead of trying to look for improper solution of extracting date, i am going to use StringFormat; whenever i require to display date.
I guess this is the optimum solution. Let me know if you guys think other ways.
Thanks once again
Upvotes: 0
Reputation: 36775
Not sure if you're looking for this: DateTime has a Property DateTime.Date. This only returns the DatePart. However you have to check for nulls before.
Update
Based on your comment, I think that you are looking for some information about nullable types. Look at this msdn-article for further information about nullable types in .net.
DateTime? is a DateTime that is nullable. Because of this, you will get null exceptions if you try to get values from its properties if it is null. Therefore you have first to check if it is null before and the accessing properties or methods such as ToShortDateString().
There is no .net native type specifically only for Dates. All dates are handled in the DateTime-structure and have a time-component. You can make your own type or handle with strings (for example DateTime.GetShortDateString returns a string). Another way to deal with this and also with null values of nullable types is to use a ValueConverter
. See here. They are usable from xaml and can handle all you want. They are very powerfull.
Upvotes: 4
Reputation: 2667
It is not clear where you want to retrieve date part in code or in xaml. Anyway in code you can do that like this:
if (Date.HasValue == true)
{
return Date.Value.ToShortDateString();
}
Upvotes: 1