Displaying the time in the local time zone in WPF/XAML

后端 未结 1 1701
-上瘾入骨i
-上瘾入骨i 2020-12-15 09:46

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 s

相关标签:
1条回答
  • 2020-12-15 10:04

    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}}" />
    
    0 讨论(0)
提交回复
热议问题