2

Im using the Datepicker control to get a date and display it in a Textblock in WP7. I want it to only show the date and not the time. The Datepicker only shows the date, but when I want to show it in the TextBlock it shows both date and time. I use databinding to set the date in the Datepicker:

public class Task
{
    public DateTime Date { get; set; }
    public Task()
    {
        Date = DateTime.Now;
    }
}

XAML:

<toolkit:DatePicker Value="{Binding Mode=TwoWay, Path=Date}" FlowDirection="RightToLeft" />
<TextBlock x:Name="TxbTaskDate" Text="{Binding Date}" />

How do I get the TextBlock to only show the date and not time?

Glenn
  • 489
  • 2
  • 7
  • 19
  • You may also need to think about localisation. Some of the answers do direct formatting with day/month/year parts but in some countries (such as the US) they do month/day/year. – aqwert Mar 18 '12 at 21:49

4 Answers4

4

You should add a StringFormat

<TextBlock x:Name="TxbTaskDate" 
           Text="{Binding Date, StringFormat='{}{0:dd.MM.yyyy}'}" />
H H
  • 263,252
  • 30
  • 330
  • 514
GuyVdN
  • 690
  • 4
  • 14
3

Try this:

<TextBlock x:Name="TxbTaskDate" Text="{Binding Date, StringFormat=d}" />
Michał
  • 895
  • 6
  • 15
1

A .NET DateTime always includes the Time. Your issue is with formatting in the TextBlock

<!-- untested -->
<TextBlock x:Name="TxbTaskDate" Text="{Binding Date StringFormat={0:dd-MM-yyyy}}" />
H H
  • 263,252
  • 30
  • 330
  • 514
0

DateTime includes a time component, as it's name suggests. You can use a ValueConverter in your TextBlock binding to strip off the time and display only the date.

At a high level, the ValueConverter will take one type, like a DateTime, and allow you to do some conversions on it. I would probably have it return a formatted string:

String.Format("{0:M/d/yyyy}", dt);

Here's a good intro to ValueConverter, if you haven't used one before.

Josh Earl
  • 18,151
  • 15
  • 62
  • 91