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!






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

excab said...

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

Anonymous said...

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

Suprotim Agarwal said...

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

Unknown said...

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