【问题标题】:Convert UTC DateTime to Local timezone in Xaml?在 Xaml 中将 UTC DateTime 转换为本地时区?
【发布时间】:2013-11-28 05:24:55
【问题描述】:

我有一个绑定到DataGrid 的项目集合。无法轻松访问集合本身,因此必须手动完成。

我在 DataGrid 上显示的成员之一是 DateTimeDateTime 虽然是 UTC,但需要以用户的本地时间显示。

XAML 中是否有一种构造可以将绑定的 DateTime 对象从 UTC 转换为本地时间?

【问题讨论】:

  • 发布 XAML 和代码。应在 DataBinding 属性中指定显示格式。这假定您的 DateTime 值设置了 DateTimeKind 属性。否则,您和 .NET 都不知道该值是 DateTimeKind.Utc 还是 DateTimeKind.Local

标签: c# wpf silverlight xaml


【解决方案1】:

您需要一个转换器来转换DateTime 值。然后,字符串格式仍然可用:

class UtcToLocalDateTimeConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      if (value is DateTime dt)
          return dt.ToLocalTime();
      else
          return DateTime.Parse(value?.ToString()).ToLocalTime();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      throw new NotImplementedException();
    }
  }

灵感来自/取自 this SO question 的更新答案,您可以在其中找到使用详情。

【讨论】:

  • 为什么只将 DateTime 值转换为 String 以将其解析回 DateTime?
  • @PanagiotisKanavos 你是对的,谢谢。如果输入已经是 DateTime 类型,现在已修复以避免 ToString/Parsing。
【解决方案2】:

我会选择这个:

public class UtcToZonedDateTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return DateTime.MinValue;
        }

        if (value is DateTime)
        {
            return ((DateTime)value).ToLocalTime();
        }

        DateTime parsedResult;
        if (DateTime.TryParse(value?.ToString(), out parsedResult))
        {
            return parsedResult.ToLocalTime();
        }

        return DateTime.MinValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 2013-09-12
    • 2019-05-31
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2011-02-02
    • 2014-08-18
    相关资源
    最近更新 更多