問題描述
我的應用程序跨多個不同設備同步數據.出于這個原因,它將所有日期存儲在 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 中顯示本地時區的時間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!