TimeSpanToStringConverter.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. var result = string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")|| string.Equals(Format, "HH:mm")
  15. ? Math.Truncate(value.TotalHours).ToString("#00") + ":" + value.Minutes.ToString("D2")
  16. : string.Format("{0:" + Format.Replace(":", "\\:") + "}", value);
  17. return result;
  18. }
  19. public override TimeSpan Deconvert(string value)
  20. {
  21. if (string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm") || string.Equals(Format, "HH:mm"))
  22. {
  23. var comps = value.Split(':');
  24. if (comps.Length == 2)
  25. {
  26. if (int.TryParse(comps[0], out int hrs) && int.TryParse(comps[1], out int mins))
  27. return new TimeSpan(hrs, mins, 0);
  28. }
  29. }
  30. else
  31. {
  32. if (TimeSpan.TryParseExact(value, Format, CultureInfo.InvariantCulture, TimeSpanStyles.None, out TimeSpan result))
  33. return result;
  34. }
  35. return TimeSpan.Zero;
  36. }
  37. }