DateToStringConverter.cs 895 B

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Globalization;
  3. using InABox.Core;
  4. namespace InABox.WPF;
  5. public class DateToStringConverter : AbstractConverter<DateTime,String>
  6. {
  7. public string Format { get; }
  8. public DateToStringConverter(string? format = null)
  9. {
  10. Format = format ?? "dd/MM/yyyy";
  11. }
  12. public override string Convert(DateTime value)
  13. {
  14. if (value is DateTime datetime && !datetime.IsEmpty())
  15. return String.Format("{0:" + Format + "}", datetime);
  16. return "";
  17. }
  18. public override DateTime Deconvert(string value)
  19. {
  20. if (String.IsNullOrWhiteSpace(value))
  21. return DateTime.MinValue;
  22. if (DateTime.TryParseExact(value, Format, CultureInfo.InvariantCulture, DateTimeStyles.None,
  23. out DateTime result))
  24. return result;
  25. return DateTime.MinValue;
  26. }
  27. }