Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying the time in the local time zone in WPF/XAML

My application synchronises data across several different devices. For this reason it stores all dates in the UTC time-zone to account for different devices possibly being set to different time zones.

The trouble is that when I read the dates back out and display them they appear to be incorrect (most of the users are on British Summer Time so they're an hour behind).

<TextBlock Margin="5" Style="{StaticResource SmallTextblockStyle}">
    <Run Text="Last Updated:" />
    <Run Text="{Binding Path=Submitted}" />
</TextBlock>

Do I need to manually override set CurrentCulture property of the UI thread? I know I have to do this in Silverlight.

like image 238
BenCr Avatar asked Jun 04 '13 15:06

BenCr


1 Answers

Are you specifying "Utc" as DateTime.Kind when parsing the stored DateTime and also converting it to DateTime.ToLocalTime()?

public DateTime Submitted {
  get {
    DateTime utcTime = DateTime.SpecifyKind(DateTime.Parse(/*"Your Stored val from DB"*/), DateTimeKind.Utc);

    return utcTime.ToLocalTime();
  }

  set {
    ...
  }
}

^^ works fine for me

Update:

class UtcToLocalDateTimeConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      return DateTime.SpecifyKind(DateTime.Parse(value.ToString()), DateTimeKind.Utc).ToLocalTime();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      throw new NotImplementedException();
    }
  }

xaml:

<Window.Resources>
  <local:UtcToLocalDateTimeConverter x:Key="UtcToLocalDateTimeConverter" />
</Window.Resources>
...
<TextBlock Text="{Binding Submitted, Converter={StaticResource UtcToLocalDateTimeConverter}}" />
like image 145
Viv Avatar answered Oct 21 '22 20:10

Viv