TimeSpanToStringConverter.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. namespace InABox.WPF;
  5. public class TimeSpanToStringConverter : AbstractConverter<TimeSpan,String>
  6. {
  7. public TimeSpanToStringConverter(string? format)
  8. {
  9. Format = format ?? "HH:mm";
  10. }
  11. public string Format { get; set; }
  12. public override string Convert(TimeSpan value)
  13. {
  14. try
  15. {
  16. var result = string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")|| string.Equals(Format, "HH:mm")
  17. ? Math.Truncate(value.TotalHours).ToString("#00") + ":" + value.Minutes.ToString("D2")
  18. : string.Format("{0:" + Format.Replace(":", "\\:") + "}", value);
  19. return result;
  20. }
  21. catch (Exception e)
  22. {
  23. return value.ToString("c");
  24. }
  25. }
  26. public override TimeSpan Deconvert(string value)
  27. {
  28. if (string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm") || string.Equals(Format, "HH:mm"))
  29. {
  30. var comps = value.Split(':');
  31. if (comps.Length == 2)
  32. {
  33. if (int.TryParse(comps[0], out int hrs) && int.TryParse(comps[1], out int mins))
  34. return new TimeSpan(hrs, mins, 0);
  35. }
  36. }
  37. else
  38. {
  39. if (TimeSpan.TryParseExact(value, Format, CultureInfo.InvariantCulture, TimeSpanStyles.None, out TimeSpan result))
  40. return result;
  41. }
  42. return TimeSpan.Zero;
  43. }
  44. }