datemath.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. ///<reference path="../../headers/common.d.ts" />
  2. import _ from 'lodash';
  3. import moment from 'moment';
  4. var units = ['y', 'M', 'w', 'd', 'h', 'm', 's'];
  5. export function parse(text, roundUp?, timezone?) {
  6. if (!text) { return undefined; }
  7. if (moment.isMoment(text)) { return text; }
  8. if (_.isDate(text)) { return moment(text); }
  9. var time;
  10. var mathString = '';
  11. var index;
  12. var parseString;
  13. if (text.substring(0, 3) === 'now') {
  14. if (timezone === 'utc') {
  15. time = moment.utc();
  16. } else {
  17. time = moment();
  18. }
  19. mathString = text.substring('now'.length);
  20. } else {
  21. index = text.indexOf('||');
  22. if (index === -1) {
  23. parseString = text;
  24. mathString = ''; // nothing else
  25. } else {
  26. parseString = text.substring(0, index);
  27. mathString = text.substring(index + 2);
  28. }
  29. // We're going to just require ISO8601 timestamps, k?
  30. time = moment(parseString, moment.ISO_8601);
  31. }
  32. if (!mathString.length) {
  33. return time;
  34. }
  35. return parseDateMath(mathString, time, roundUp);
  36. }
  37. export function isValid(text) {
  38. var date = parse(text);
  39. if (!date) {
  40. return false;
  41. }
  42. if (moment.isMoment(date)) {
  43. return date.isValid();
  44. }
  45. return false;
  46. }
  47. export function parseDateMath(mathString, time, roundUp?) {
  48. var dateTime = time;
  49. var i = 0;
  50. var len = mathString.length;
  51. while (i < len) {
  52. var c = mathString.charAt(i++);
  53. var type;
  54. var num;
  55. var unit;
  56. if (c === '/') {
  57. type = 0;
  58. } else if (c === '+') {
  59. type = 1;
  60. } else if (c === '-') {
  61. type = 2;
  62. } else {
  63. return undefined;
  64. }
  65. if (isNaN(mathString.charAt(i))) {
  66. num = 1;
  67. } else if (mathString.length === 2) {
  68. num = mathString.charAt(i);
  69. } else {
  70. var numFrom = i;
  71. while (!isNaN(mathString.charAt(i))) {
  72. i++;
  73. if (i > 10) { return undefined; }
  74. }
  75. num = parseInt(mathString.substring(numFrom, i), 10);
  76. }
  77. if (type === 0) {
  78. // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M)
  79. if (num !== 1) {
  80. return undefined;
  81. }
  82. }
  83. unit = mathString.charAt(i++);
  84. if (!_.includes(units, unit)) {
  85. return undefined;
  86. } else {
  87. if (type === 0) {
  88. if (roundUp) {
  89. dateTime.endOf(unit);
  90. } else {
  91. dateTime.startOf(unit);
  92. }
  93. } else if (type === 1) {
  94. dateTime.add(num, unit);
  95. } else if (type === 2) {
  96. dateTime.subtract(num, unit);
  97. }
  98. }
  99. }
  100. return dateTime;
  101. }