#VS2017 – Xaml Converter to display local UTC date times

Hi !

Visual Studio Live at Austin will start soon, so I’ll pick up some of my drafts for a quick post.

How to create an XAML Converter to display a DateTime value in the local current format of the machine running the App

The converter code is very simple


using System;
using Windows.UI.Xaml.Data;
namespace ElBruno.UI.Converters
{
public class UtcToLocalDateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return DateTime.SpecifyKind(DateTime.Parse(value.ToString()), DateTimeKind.Utc).ToLocalTime();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}

And the way to use it is also very easy


<Page
…>
<Page.Resources>
<converters:UtcToLocalDateTimeConverter x:Key="UtcToLocalDateTimeConverter" />
</Page.Resources>
<TextBlock TextAlignment="Center"
Run Text="{Binding SomeEntity.Date, Converter={StaticResource UtcToLocalDateTimeConverter}}" />
</TextBlock>
</Page>

So I’ll leave it here so I’ll save some search time ! 😀

Greetings @ Austin VSLive

El Bruno

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.