DateTimeTickUnitBase.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. namespace ScottPlot.Ticks.DateTimeTickUnits
  6. {
  7. public class DateTimeTickUnitBase : IDateTimeUnit
  8. {
  9. // base class implements Seconds Unit
  10. protected DateTimeUnit kind = DateTimeUnit.Second;
  11. protected CultureInfo culture;
  12. protected int[] deltas = new int[] { 1, 2, 5, 10, 15, 30 };
  13. protected int maxTickCount;
  14. public DateTimeTickUnitBase(CultureInfo culture, int maxTickCount, int? manualSpacing)
  15. {
  16. this.culture = culture;
  17. this.maxTickCount = maxTickCount;
  18. if (manualSpacing.HasValue)
  19. deltas = new int[] { manualSpacing.Value };
  20. }
  21. protected virtual DateTime Floor(DateTime value)
  22. {
  23. return new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, 0);
  24. }
  25. protected virtual DateTime Increment(DateTime value, int delta)
  26. {
  27. return value.AddSeconds(delta);
  28. }
  29. protected virtual string GetTickLabel(DateTime value)
  30. {
  31. string date = value.ToString("d", culture); // short date
  32. string time = value.ToString("T", culture); // long time
  33. return $"{date}\n{time}";
  34. }
  35. public (double[] Ticks, string[] Labels) GetTicksAndLabels(DateTime from, DateTime to, string format)
  36. {
  37. DateTime[] ticks = GetTicks(from, to, deltas, maxTickCount);
  38. string[] labels = (format is null) ?
  39. ticks.Select(t => GetTickLabel(t)).ToArray() :
  40. ticks.Select(t => t.ToString(format, culture)).ToArray();
  41. return (ticks.Select(t => t.ToOADate()).ToArray(), labels);
  42. }
  43. protected DateTime[] GetTicks(DateTime from, DateTime to, int[] deltas, int maxTickCount)
  44. {
  45. DateTime[] result = new DateTime[] { };
  46. foreach (var delta in deltas)
  47. {
  48. result = GetTicks(from, to, delta);
  49. if (result.Length <= maxTickCount)
  50. return result;
  51. }
  52. return result;
  53. }
  54. protected virtual DateTime[] GetTicks(DateTime from, DateTime to, int delta)
  55. {
  56. var dates = new List<DateTime>();
  57. DateTime dt = Floor(from);
  58. while (dt <= to)
  59. {
  60. if (dt >= from)
  61. dates.Add(dt);
  62. try
  63. {
  64. dt = Increment(dt, delta);
  65. }
  66. catch
  67. {
  68. break; // our date is larger than possible
  69. }
  70. }
  71. return dates.ToArray();
  72. }
  73. }
  74. }