Silverlight DateTime Format on Mac

The Problem

I recently discovered that the default Silverlight DateTime format is different on MacOS than it is in Windows.

 

On Windows

windows

 

On MacOS

mac

 

There are a couple of differences, but the most noticeable is that time zone offset at the end of the time that shows on the Mac. On my computer the time zone offset shows as “-4:00” because I’m generating a DateTime in local time, which for me is currently Eastern Daylight Time (EDT), or 4 hours behind Coordinated Universal Time (UTC).

 

The application is following the best practice of storing all DateTimes in UTC. However, because the times were being displayed to the user in their correct local time zone, my client wanted the time zone offset removed from the end of the date.

 

That could easily be solved by adding a FormatString to the binding statement. The challenge was to remove the time zome offset while still taking into account all the other localized DateTime formatting, such as the different order for the month and day in a US versus a Europe date (7/4/2012 being July 4 in the US and April 7 in Europe).

 

The Solution

I created a IValueConverter class to convert my DateTime to a string and added it to the binding.
 
<TextBlock Text="{Binding SampleDate, Converter={StaticResource DateDisplayConverter}}" />
 
This DateTime-to-string conversion happens automatically anyway in the binding of a DateTime value to a string property such as TextBlock.Text. If you don’t do the conversion yourself or specify a format string in the binding, then the default format string of “G” is used, which is equivalent to “M/dd/yyyy h:mm:ss tt” on US-based Windows machines and “M/dd/yy h:mm:ss tt zzzz” on US-based Macs.
 
Inside the value converter I use the CultureInfo class to get the default date and time formats for the user’s local culture and then remove the time zone offset (“zzzz”) if it is there.
 
public class DateDisplayConverter: IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
DateTime val = (DateTime)value;
string localDateFormatString =
CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
+ " "
+ CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern.Replace(" zzzz", "");
return val.ToString(localDateFormatString);
}

public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return DateTime.Parse(value.ToString());
}
}

As you can see below, using this value converter results in the same DateTime displayed without applying any format string, with the addition benefit of removing the time zone offset on the Mac.
 

Windows

windows2

 

MacOS

mac2
 
In the screen shots below, you can see that the formatting still correctly reflects the user’s locality (in this case, the UK) while still removing the time zone offset.
 

Windows (UK)

windows3
 

MacOS (UK)

mac3

comments powered by Disqus