Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}}" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...