WPF format DateTime in TextBlock?
Asked Answered
P

4

81

I have a TextBlock that is bound to a DateTime property. How do I configure the format of the date?

Pluralize answered 26/8, 2009 at 7:58 Comment(0)
R
157

There is a string format property available when you are declaring the binding:

<TextBox Text="{Binding Path=DateTimeValue, StringFormat=dd-MM-yyyy}" />

(You need to be on .NET 3.5 SP1 for this property to exist)

Ranged answered 26/8, 2009 at 8:2 Comment(1)
Just letting you know this is now TextBox <- capital BNeisa
P
39

If you want to use a common format string between bindings, you could declare the binding like this:

<Textbox Text={Binding Path=DateTimeValue, StringFormat={x:Static local:Constants.DateTimeUiFormat}} />

With your constants class like this:

public static class Constants
{
    public const string DateTimeUiFormat = "dd/MM/yyyy";

    //etc...
}
Piemonte answered 26/9, 2012 at 2:29 Comment(1)
Thanks Brian! I used this in combination with System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern to get an i18n short date.Alevin
N
29

May be helpful to someone:

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
           StringFormat='{}{0: Today is dddd, MMMM dd, yyyy, hh:mm:ss}'}"/>

or 24h and 2digits month and year format:

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
           StringFormat='{}{0: Today is dddd, MM.dd.yy, HH:mm:ss}'}"/>
Nebo answered 20/9, 2016 at 11:47 Comment(0)
H
0
<TextBlock Text="{Binding Path=DateTimeValue, StringFormat='Today is {0: dd/MM/yyyy}'}" />
Highboy answered 24/3 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.