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?
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With