dates.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import moment from 'moment';
  2. import {DateTimeObject} from 'sentry/components/charts/utils';
  3. import {DateString} from 'sentry/types';
  4. import {getPeriodAgo, getUtcDateString, parsePeriodToHours} from 'sentry/utils/dates';
  5. function midTimestamp(start: DateString, end: DateString): string {
  6. const diff = moment(end).diff(moment(start));
  7. const middle = moment(start).add(diff / 2);
  8. return getUtcDateString(middle);
  9. }
  10. export function getMiddleTimestamp({
  11. start,
  12. end,
  13. statsPeriod,
  14. }: {
  15. end?: string;
  16. start?: string;
  17. statsPeriod?: string;
  18. }) {
  19. if (statsPeriod) {
  20. const rangeStart = getPeriodAgo('hours', parsePeriodToHours(statsPeriod)).toDate();
  21. const rangeEnd = new Date();
  22. return midTimestamp(rangeStart, rangeEnd);
  23. }
  24. if (!start || !end) {
  25. throw new Error('start and end required');
  26. }
  27. return midTimestamp(start, end);
  28. }
  29. export const PERIOD_REGEX = /^(\d+)([h,d])$/;
  30. export const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss';
  31. export const datetimeToClickhouseFilterTimestamps = (datetime?: DateTimeObject) => {
  32. if (!datetime) {
  33. return {};
  34. }
  35. const [_, num, unit] = datetime.period?.match(PERIOD_REGEX) ?? [];
  36. const start_timestamp =
  37. (datetime.start && moment(datetime.start).format(DATE_FORMAT)) ??
  38. (num &&
  39. unit &&
  40. moment()
  41. .subtract(num, unit as 'h' | 'd')
  42. .format(DATE_FORMAT));
  43. const end_timestamp = datetime.end && moment(datetime.end).format(DATE_FORMAT);
  44. return {start_timestamp, end_timestamp};
  45. };
  46. export function getDateFilters(pageFilter) {
  47. const [_, num, unit] = pageFilter.selection.datetime.period?.match(PERIOD_REGEX) ?? [];
  48. const startTime =
  49. num && unit
  50. ? moment().subtract(num, unit as 'h' | 'd')
  51. : moment(pageFilter.selection.datetime.start);
  52. const endTime = moment(pageFilter.selection.datetime.end ?? undefined);
  53. return {startTime, endTime};
  54. }