time.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { TimeRange, TIME_FORMAT, RawTimeRange, TimeZone } from '../../types/time';
  2. import { describeTimeRange } from '../../utils/rangeutil';
  3. import * as dateMath from '../../utils/datemath';
  4. import { isDateTime, dateTime, DateTime, toUtc } from '../../utils/moment_wrapper';
  5. export const rawToTimeRange = (raw: RawTimeRange, timeZone?: TimeZone): TimeRange => {
  6. const from = stringToDateTimeType(raw.from, false, timeZone);
  7. const to = stringToDateTimeType(raw.to, true, timeZone);
  8. return { from, to, raw };
  9. };
  10. export const stringToDateTimeType = (value: string | DateTime, roundUp?: boolean, timeZone?: TimeZone): DateTime => {
  11. if (isDateTime(value)) {
  12. return value;
  13. }
  14. if (value.indexOf('now') !== -1) {
  15. if (!dateMath.isValid(value)) {
  16. return dateTime();
  17. }
  18. const parsed = dateMath.parse(value, roundUp, timeZone);
  19. return parsed || dateTime();
  20. }
  21. if (timeZone === 'utc') {
  22. return toUtc(value, TIME_FORMAT);
  23. }
  24. return dateTime(value, TIME_FORMAT);
  25. };
  26. export const mapTimeRangeToRangeString = (timeRange: RawTimeRange): string => {
  27. return describeTimeRange(timeRange);
  28. };
  29. export const isValidTimeString = (text: string) => dateMath.isValid(text);