Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supply fixed now to datemath caluclations #981

Merged
merged 9 commits into from
Dec 13, 2024
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
Loading