Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
DateTimeToStringConverter.cs
1using System;
2using System.Globalization;
3using Microsoft.Maui.Controls;
4
6{
11 public class DateTimeToStringConverter : IValueConverter
12 {
14 public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
15 {
16 if (value is not DateTime DateTime)
17 return string.Empty;
18
19 bool ForceUtc = IsForceUtc(parameter);
20
21 DateTime Formatted = ForceUtc ? DateTime.ToUniversalTime() : DateTime;
22 bool DateOnly = IsDateOnly(Formatted);
23
24 string Result = DateOnly
25 ? Formatted.ToString("d", culture)
26 : Formatted.ToString("G", culture);
27
28 if (Formatted.Kind == DateTimeKind.Utc || ForceUtc)
29 Result = $"{Result} (UTC)";
30
31 return Result;
32 }
33
35 public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
36 {
37 if (value is string s && DateTime.TryParse(s, culture, DateTimeStyles.None, out DateTime Parsed))
38 return Parsed;
39
40 return DateTime.MinValue;
41 }
42
43 private static bool IsDateOnly(DateTime dateTime)
44 {
45 return dateTime.TimeOfDay == TimeSpan.Zero;
46 }
47
48 private static bool IsForceUtc(object? parameter)
49 {
50 if (parameter is null)
51 return false;
52
53 if (parameter is bool BoolParam)
54 return BoolParam;
55
56 if (parameter is string StrParam)
57 return string.Equals(StrParam, "utc", StringComparison.OrdinalIgnoreCase);
58
59 return false;
60 }
61 }
62}
Converts DateTime values into localized strings, optionally forcing UTC output. Date-only formatting ...
object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)