Convert UTC DateTime to Local timezone in Xaml?
c#, silverlight, wpf, xaml
Solution
You'll need a converter to transform the `DateTime` value. Then, string formatting remains available as usual:
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();
}
}
Inspired/Taken by/from the Updated answer of this SO question where you'll find usage details.
Problem
I've got a collection of items that's bound to a `DataGrid`. There is no easy access to the collection itself hence this has to be done manually. One of the members I'm displaying on the DataGrid is a `DateTime`. The `DateTime` is in UTC though, and needs to be displayed in user's local time. Is there a construct in XAML which will let one convert the bound `DateTime` object from UTC to Local time?