显示时间在WPF / XAML本地时区 [英] Displaying the time in the local time zone in WPF/XAML

查看:632
本文介绍了显示时间在WPF / XAML本地时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序同步更新在几个不同设备的数据。出于这个原因,它存储在UTC时区的所有日期来解释可能被设置为不同的时区不同的设备。

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>



我是否需要手动覆盖UI线程设置CurrentCulture属性?我知道我必须这样做在Silverlight。

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

推荐答案

您指定UTC为的DateTime.Kind 当解析存储的DateTime ,也将其转换为的 DateTime.ToLocalTime()

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 {
    ...
  }
}

^^我

更新工作正常:

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:

xaml:

<Window.Resources>
  <local:UtcToLocalDateTimeConverter x:Key="UtcToLocalDateTimeConverter" />
</Window.Resources>
...
<TextBlock Text="{Binding Submitted, Converter={StaticResource UtcToLocalDateTimeConverter}}" />

这篇关于显示时间在WPF / XAML本地时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆