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

查看:62
本文介绍了在 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 线程的 set 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:

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

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

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