DFLayoutTimeFieldProperties.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Globalization;
  4. namespace InABox.Core
  5. {
  6. public class DFLayoutTimeFieldProperties : DFLayoutFieldProperties<TimeSpan, TimeSpan?>
  7. {
  8. public DFLayoutTimeFieldProperties()
  9. {
  10. Format = "hh:mm";
  11. }
  12. public string Format { get; set; }
  13. public override string FormatValue(TimeSpan? value)
  14. {
  15. var time = value ?? default;
  16. return string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")
  17. ? Math.Truncate(time.TotalHours).ToString("#00") + ":" + time.Minutes.ToString("D2")
  18. : string.Format("{0:" + Format.Replace(":", "\\:") + "}", time);
  19. }
  20. public override void SerializeValue(DFSaveStorageEntry entry, TimeSpan? value)
  21. {
  22. if (value.HasValue)
  23. {
  24. entry.SetValue(value.Value.ToString("c"));
  25. }
  26. }
  27. public override TimeSpan? DeserializeValue(DFLoadStorageEntry entry)
  28. {
  29. var value = entry.GetValue();
  30. if (value is TimeSpan time)
  31. return time;
  32. if (TimeSpan.TryParseExact(value as string, "c", CultureInfo.InvariantCulture, TimeSpanStyles.None, out var result))
  33. return result;
  34. return null;
  35. }
  36. public override TimeSpan GetValue(TimeSpan? value)
  37. {
  38. return value ?? Default;
  39. }
  40. protected override void LoadProperties()
  41. {
  42. base.LoadProperties();
  43. Format = GetProperty("Format", "hh:mm");
  44. }
  45. protected override void SaveProperties()
  46. {
  47. base.SaveProperties();
  48. SetProperty("Format", Format);
  49. }
  50. }
  51. }