53

I have a set up XAML code below.

<Label Text="{Binding Date}"></Label>
<Label Text="{Binding Time}'}"></Label>

I want result like september 12,2014 2:30 PM.

3

4 Answers 4

174

Change your code to:

<Label Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}'}"></Label>
<Label Text="{Binding Time, StringFormat='{}{0:hh\\:mm}'}"></Label>
2
  • 54
    Googled this and found my own answer. First two answers are useless but this one solves it. Good job me!
    – User1
    Dec 7, 2015 at 12:20
  • 2
    This saved me a lot of time. This should be accepted answer...
    – Xonshiz
    Jul 20, 2020 at 18:02
13

Make a custom IValueConverter implementation:

public class DatetimeToStringConverter : IValueConverter
{
    #region IValueConverter implementation

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return string.Empty;

        var datetime = (DateTime)value;
        //put your custom formatting here
        return datetime.ToLocalTime().ToString("g");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException(); 
    }

    #endregion
}

Then use it like that:

<ResourceDictionary>
    <local:DatetimeToStringConverter x:Key="cnvDateTimeConverter"></local:DatetimeToStringConverter>
</ResourceDictionary>

...

<Label Text="{Binding Date, Converter={StaticResource cnvDateTimeConverter}}"></Label>
<Label Text="{Binding Time, Converter={StaticResource cnvDateTimeConverter}}"></Label>
2
  • I try your code, but getting invalid cast exception on the line, var datetime = (DateTime)value; For me receiving the date as a java timestamp: 1510822596449. Is your code working for fine for converting java timestamp to string date?
    – user4458270
    Dec 7, 2017 at 5:33
  • Me too, i tried your code then i got a invalid cast exception. Sep 8, 2020 at 16:31
9
<Label>

<Label.FormattedText>

<FormattedString>

<Span Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}'}"/>
<Span Text=" "/>
<Span Text="{Binding Time, StringFormat='{0:h:mm tt}'}"/>

</FormattedString>

</Label.FormattedText>

</Label>
6

Use the standard .NET Date Format specifiers.

To get

September 12, 2014 2:30 PM

use something like

MMMM d, yyyy h:mm tt
3
  • Date is binding as expected but time is not , it only displays 2: 30 but not 2:30 PM where time is a TimeSpan
    – Narendra
    Sep 28, 2015 at 8:36
  • 2
    a TimeSpan represents an interval - it does not have a concept of AM/PM
    – Jason
    Sep 28, 2015 at 13:31
  • Can you provide the XAML please
    – niico
    Nov 6, 2019 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.