time.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import moment, { Moment } from 'moment';
  2. import { TimeOption, TimeRange, TIME_FORMAT } from '@grafana/ui';
  3. import * as dateMath from '@grafana/ui/src/utils/datemath';
  4. import { describeTimeRange } from '@grafana/ui/src/utils/rangeutil';
  5. export const mapTimeOptionToTimeRange = (
  6. timeOption: TimeOption,
  7. isTimezoneUtc: boolean,
  8. timezone?: dateMath.Timezone
  9. ): TimeRange => {
  10. const fromMoment = stringToMoment(timeOption.from, isTimezoneUtc, false, timezone);
  11. const toMoment = stringToMoment(timeOption.to, isTimezoneUtc, true, timezone);
  12. return { from: fromMoment, to: toMoment, raw: { from: timeOption.from, to: timeOption.to } };
  13. };
  14. export const stringToMoment = (
  15. value: string,
  16. isTimezoneUtc: boolean,
  17. roundUp?: boolean,
  18. timezone?: dateMath.Timezone
  19. ): Moment => {
  20. if (value.indexOf('now') !== -1) {
  21. if (!dateMath.isValid(value)) {
  22. return moment();
  23. }
  24. const parsed = dateMath.parse(value, roundUp, timezone);
  25. return parsed || moment();
  26. }
  27. if (isTimezoneUtc) {
  28. return moment.utc(value, TIME_FORMAT);
  29. }
  30. return moment(value, TIME_FORMAT);
  31. };
  32. export const mapTimeRangeToRangeString = (timeRange: TimeRange): string => {
  33. return describeTimeRange(timeRange.raw);
  34. };
  35. export const isValidTimeString = (text: string) => dateMath.isValid(text);