6

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?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
cost
  • 4,420
  • 8
  • 48
  • 80
  • Post the XAML and code. Display formats should be specified in the DataBinding attribute. This assumes that your DateTime value has the DateTimeKind attribute set. Otherwise neither you nor .NET really knows whether the value is DateTimeKind.Utc or DateTimeKind.Local – Panagiotis Kanavos Apr 07 '16 at 14:07

2 Answers2

12

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Askolein
  • 3,250
  • 3
  • 28
  • 40
2

I would go with this one:

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();
    }
}
Athanviel
  • 199
  • 1
  • 3
  • 15
Gabriel Robert
  • 3,012
  • 2
  • 18
  • 36