如何将 Microsoft Graph dateTimeTimeZone 转换为本地 DateTime?

How to convert Microsoft Graph dateTimeTimeZone to local DateTime?

Microsoft Graph the datetime values (for example in events of outlook) are returned as an instance of DateTimeTimeZoneclass。该对象由两个字符串属性( datetime 和 timezone )组成,表示 UTC 日期。在 UWP 应用程序中,我们可以使用 value converter 控制这些值的显示方式,如下所示:

问题IValueConverter Interface used in the following code is from a UWP Windows.UI.Xaml.Data 命名空间。我们如何在 WPF 应用程序中实现相同的目标?

using Microsoft.Graph;
using System;

class GraphDateTimeTimeZoneConverter : Windows.UI.Xaml.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            DateTimeTimeZone date = value as DateTimeTimeZone;

            if (date != null)
            {
                // Resolve the time zone
                var timezone = TimeZoneInfo.FindSystemTimeZoneById(date.TimeZone);
                // Parse method assumes local time, which may not be the case
                var parsedDateAsLocal = DateTimeOffset.Parse(date.DateTime);
                // Determine the offset from UTC time for the specific date
                // Making this call adjusts for DST as appropriate
                var tzOffset = timezone.GetUtcOffset(parsedDateAsLocal.DateTime);
                // Create a new DateTimeOffset with the specific offset from UTC
                var correctedDate = new DateTimeOffset(parsedDateAsLocal.DateTime, tzOffset);
                // Return the local date time string
                return correctedDate.LocalDateTime.ToString();
            }

            return string.Empty;
        }

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

UWP Xaml:

<Page
    x:Class="MyMSGraphProject.CalendarPage"
   ....
</Page>

<Page.Resources>
    <local:GraphDateTimeTimeZoneConverter x:Key="DateTimeTimeZoneValueConverter" />
</Page.Resources>

<Grid>
  <DataGrid x:Name="EventList" AutoGenerateColumns="False">
      <DataGrid.Columns>
         <DataGridTextColumn Header="Birth Date" Binding="{Binding BirthDate, Converter={StaticResource DateTimeTimeZoneValueConverter}}" />
      .....
      </DataGrid.Columns>
  </DataGrid>
</Grid>

上面DataGrid的显示快照:

WPF 具有非常相似的 System.Windows.Data.IValueConverter interface

本文档介绍了如何从 Windows 桌面应用程序添加对 UWP 库的引用:Call Windows Runtime APIs in desktop apps

使用上面的方法,您可以创建一个 System.Windows.Data.IValueConverter,它引用 DateTimeTimeZone 类型并进行适当的转换,就像您当前的 Windows.UI.Xaml.Data.IValueConverter 所做的那样。