In Microsoft Graph the datetime values (for example in events of outlook) are returned as an instance of DateTimeTimeZone class. This object is composed by two properties ( datetime and timezone ) that are strings, and represents a UTC date. In a UWP app, we can control how those values are displayed by using a value converter as follows:
Question: The IValueConverter Interface used in the following code is from a UWP Windows.UI.Xaml.Data Namespace. How can we achieve the same in a WPF app?
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>
Snapshot of the display of the above DataGrid:
