Skip to content

Commit 2342ba4

Browse files
authored
Supply fixed now to datemath caluclations (#981)
1 parent 639cac0 commit 2342ba4

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

packages/scenes/src/utils/evaluateTimeRange.ts

+35-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { dateMath, DateTime, TimeRange } from '@grafana/data';
1+
import { dateMath, DateTime, DateTimeInput, TimeRange } from '@grafana/data';
22
import { TimeZone } from '@grafana/schema';
33

44
export function evaluateTimeRange(
@@ -9,10 +9,42 @@ export function evaluateTimeRange(
99
delay?: string
1010
): TimeRange {
1111
const hasDelay = delay && to === 'now';
12+
const now = Date.now();
1213

14+
/** This tries to use dateMath.toDateTime if available, otherwise falls back to dateMath.parse.
15+
* Using dateMath.parse can potentially result in to and from being calculated using two different timestamps.
16+
* If two different timestamps are used, the time range "now-24h to now" will potentially be 24h +- number of milliseconds it takes between calculations.
17+
*/
18+
const parseOrToDateTime = (
19+
val: string | DateTime,
20+
options: { roundUp: boolean; timezone: TimeZone; fiscalYearStartMonth?: number; now?: DateTimeInput }
21+
) => {
22+
// @ts-ignore
23+
if (dateMath.toDateTime) {
24+
// @ts-ignore
25+
return dateMath.toDateTime(val, options);
26+
} else {
27+
return dateMath.parse(val, options.roundUp, options.timezone, options.fiscalYearStartMonth);
28+
}
29+
};
30+
31+
/** 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.
32+
* 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
33+
* from the timerange indeterminently alternating between less than or equal to 24h and being greater than 24h.
34+
*/
1335
return {
14-
from: dateMath.parse(from, false, timeZone, fiscalYearStartMonth)!,
15-
to: dateMath.parse(hasDelay ? 'now-' + delay : to, true, timeZone, fiscalYearStartMonth)!,
36+
to: parseOrToDateTime(hasDelay ? 'now-' + delay : to, {
37+
roundUp: true,
38+
timezone: timeZone,
39+
fiscalYearStartMonth: fiscalYearStartMonth,
40+
now: now,
41+
})!,
42+
from: parseOrToDateTime(from, {
43+
roundUp: false,
44+
timezone: timeZone,
45+
fiscalYearStartMonth: fiscalYearStartMonth,
46+
now: now,
47+
})!,
1648
raw: {
1749
from: from,
1850
to: to,

0 commit comments

Comments
 (0)