Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UTC DateTime to Local timezone in Xaml?

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?

like image 535
cost Avatar asked Feb 15 '23 13:02

cost


2 Answers

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.

like image 188
Askolein Avatar answered Feb 17 '23 01:02

Askolein


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();
    }
}
like image 31
Gabriel Robert Avatar answered Feb 17 '23 02:02

Gabriel Robert