Skip to content

Commit

Permalink
Supply fixed now to datemath caluclations (#981)
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarkilhed authored Dec 13, 2024
1 parent 639cac0 commit 2342ba4
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions packages/scenes/src/utils/evaluateTimeRange.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dateMath, DateTime, TimeRange } from '@grafana/data';
import { dateMath, DateTime, DateTimeInput, TimeRange } from '@grafana/data';
import { TimeZone } from '@grafana/schema';

export function evaluateTimeRange(
Expand All @@ -9,10 +9,42 @@ export function evaluateTimeRange(
delay?: string
): TimeRange {
const hasDelay = delay && to === 'now';
const now = Date.now();

/** This tries to use dateMath.toDateTime if available, otherwise falls back to dateMath.parse.
* Using dateMath.parse can potentially result in to and from being calculated using two different timestamps.
* If two different timestamps are used, the time range "now-24h to now" will potentially be 24h +- number of milliseconds it takes between calculations.
*/
const parseOrToDateTime = (
val: string | DateTime,
options: { roundUp: boolean; timezone: TimeZone; fiscalYearStartMonth?: number; now?: DateTimeInput }
) => {
// @ts-ignore
if (dateMath.toDateTime) {
// @ts-ignore
return dateMath.toDateTime(val, options);
} else {
return dateMath.parse(val, options.roundUp, options.timezone, options.fiscalYearStartMonth);
}
};

/** The order of calculating to and from is important. This is because if we're using the old dateMath.parse we could potentially get two different timestamps.
* If we calculate to first, then from. The timerange "now-24h to now" will err on the side of being shorter than 24h. This will aleviate some of the issues arising
* from the timerange indeterminently alternating between less than or equal to 24h and being greater than 24h.
*/
return {
from: dateMath.parse(from, false, timeZone, fiscalYearStartMonth)!,
to: dateMath.parse(hasDelay ? 'now-' + delay : to, true, timeZone, fiscalYearStartMonth)!,
to: parseOrToDateTime(hasDelay ? 'now-' + delay : to, {
roundUp: true,
timezone: timeZone,
fiscalYearStartMonth: fiscalYearStartMonth,
now: now,
})!,
from: parseOrToDateTime(from, {
roundUp: false,
timezone: timeZone,
fiscalYearStartMonth: fiscalYearStartMonth,
now: now,
})!,
raw: {
from: from,
to: to,
Expand Down

0 comments on commit 2342ba4

Please sign in to comment.