dates.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. .startOf('minute')
  43. .format(DATE_FORMAT));
  44. const end_timestamp = datetime.end && moment(datetime.end).format(DATE_FORMAT);
  45. return {start_timestamp, end_timestamp};
  46. };
  47. export function getDateFilters(pageFilter) {
  48. const [_, num, unit] = pageFilter.selection.datetime.period?.match(PERIOD_REGEX) ?? [];
  49. const startTime =
  50. num && unit
  51. ? moment().subtract(num, unit as 'h' | 'd')
  52. : moment(pageFilter.selection.datetime.start);
  53. const endTime = moment(pageFilter.selection.datetime.end ?? undefined);
  54. return {startTime, endTime};
  55. }