May 22, 2010

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!



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

4 Responses to "Format Date in Silverlight 4"
  1. excab said...
    June 27, 2010 8:45 AM

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

  2. Anonymous said...
    August 6, 2010 1:58 PM

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

  3. Suprotim Agarwal said...
    August 6, 2010 6:18 PM

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

  4. Unknown said...
    May 17, 2012 8:14 AM

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

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions