Format Date in Silverlight 4

In Silverlight 3, to format a date, you needed to write a Converter class that implemented the IValueConverter interface and you needed to implement the Convert and ConvertBack methods – something similar to the following:

public class DateConverter: IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
DateTime dt = (DateTime)value;
return dt.ToShortDateString();
}

public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
string str = value.ToString();
DateTime dt = DateTime.MinValue;

if (DateTime.TryParse(str, out dt))
{
return dt;
}
return value;
}
}

You then needed to add a reference to your class and write the following markup to format the date

<TextBox Text="{Binding Path=SomeDate,
Converter={StaticResource DateConverter}}" />

Silverlight 4 introduces the StringFormat binding property that makes formatting absolutely simple. You can format a value using either a predefined format or a custom format and the best part is, you do not need to write a converter class.

So to format a date in “dd/MM/yyyy” format, all you need to do is write the following markup

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

which will produce the output 18/05/2010. Simple is good!

4 comments:

  1. Apparently not - I just tried StringFormat='dd/mm/yyyy' and the date returned was 27/43/2010 ????

    ReplyDelete
  2. The "mm" format string will return the minutes for the DateTime. You should use 'dd/MM/yyyy' instead, where "MM" returns the month.

    ReplyDelete
  3. Yes! that was an error on my part. Corrected.

    ReplyDelete
  4. it shows time also. how to show date only from datetime?

    ReplyDelete