Format date with StringFormat in TextBlock in WPF

这一生的挚爱 提交于 2021-01-29 06:22:01

问题


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=?????" 

回答1:


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\}}"/>



回答2:


Try the DateTime.ParseExact method:

  dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
  format = "ddd dd MMM yyyy h:mm tt zzz";
  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }

in your case i believe that the format should be:

 format = "yyyyMMdd";

for more info: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx



来源:https://stackoverflow.com/questions/10971620/format-date-with-stringformat-in-textblock-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!