using System; using System.Globalization; using System.Linq; namespace InABox.WPF; public class TimeSpanToStringConverter : UtilityConverter { public TimeSpanToStringConverter(string? format) { Format = format ?? "HH:mm"; } public string Format { get; set; } public override string Convert(TimeSpan value) { var result = string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")|| string.Equals(Format, "HH:mm") ? Math.Truncate(value.TotalHours).ToString("#00") + ":" + value.Minutes.ToString("D2") : string.Format("{0:" + Format.Replace(":", "\\:") + "}", value); return result; } public override TimeSpan Deconvert(string value) { if (string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm") || string.Equals(Format, "HH:mm")) { var comps = value.Split(':'); if (comps.Length == 2) { if (int.TryParse(comps[0], out int hrs) && int.TryParse(comps[1], out int mins)) return new TimeSpan(hrs, mins, 0); } } else { if (TimeSpan.TryParseExact(value, Format, CultureInfo.InvariantCulture, TimeSpanStyles.None, out TimeSpan result)) return result; } return TimeSpan.Zero; } }