0

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=?????" 
2
  • Update your database, do not do it on the client. StringFormat won't help you anyway, but you might use converter Commented Jun 10, 2012 at 19:21
  • I have to do it because i'm using Persian Date Time .. and i don't have equivalent control either in UI nor I have this type in Sql server ... and I NEED a formatter to do this Commented Jun 10, 2012 at 19:25

2 Answers 2

4

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\}}"/>
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Thanks very much introducing this method but I want to use this formatter in a Binding .. so i need a way to do it in Xaml not in C#
Couldn't get it from your question before it was edited... sorry that i couldn't help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.