在 WPF/XAML 中显示本地时区的时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16921711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying the time in the local time zone in WPF/XAML
提问by BenCr
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.
我的应用程序跨多个不同设备同步数据。出于这个原因,它将所有日期存储在 UTC 时区,以考虑可能设置为不同时区的不同设备。
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.
我是否需要手动覆盖 UI 线程的设置 CurrentCulture 属性?我知道我必须在 Silverlight 中执行此操作。
回答by Viv
Are you specifying "Utc" as DateTime.Kindwhen parsing the stored DateTimeand also converting it to DateTime.ToLocalTime()?
在解析存储并将其转换为DateTime.ToLocalTime()时,您是否将“Utc”指定为DateTime.Kind?DateTime
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:
xml:
<Window.Resources>
<local:UtcToLocalDateTimeConverter x:Key="UtcToLocalDateTimeConverter" />
</Window.Resources>
...
<TextBlock Text="{Binding Submitted, Converter={StaticResource UtcToLocalDateTimeConverter}}" />

