Search code examples
wpftextblockstring-formatting

Format date with StringFormat in TextBlock in WPF


I have stored date in database without slashing for some reason . it means that I have a date field like 20110602.

As i want to retrieve this date and show it in a textblock I need a formatting to show this date as a normal date with slash.

How can i use StringFormat in this way ? ... does anyone konw what format should I use to convert "20110602" to 2011/06/02 ?

<TextBlock  Text="{Binding CreatedDate, StringFormat=?????" 

Solution

  • If you perfer the route of implementing a converter:

    class dateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string dateString = (string)value;
            return DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Then in your xaml

    <TextBlock Text="{Binding Path=<path>, Converter={StaticResource <dateTimeConverterKey>}, StringFormat=\{0:yyyy/MM/dd\}}"/>