Skip to content

Commit e14dcb2

Browse files
authored
[APM] Correct timezone formatting (#48355)
* Don't set the timezone anywhere in APM since it's already set in autoload For the chart X-axes: * Create nice ticks for the configured timezone (ie at 1w, 1d, 12hrs interval) by offsetting the xMin/xMax * Explicitly pass those tick values to the x-axis * When formatting, use scaleUtc to format everything as UTC, and offset the time again with the configured timezone. Fixes #47832 Fixes #48355
1 parent fa74cf0 commit e14dcb2

9 files changed

Lines changed: 186 additions & 43 deletions

File tree

‎x-pack/legacy/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx‎

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,10 @@ import {
2626
} from '@elastic/eui';
2727
import { i18n } from '@kbn/i18n';
2828
import { FormattedMessage } from '@kbn/i18n/react';
29-
import { memoize, padLeft, range } from 'lodash';
29+
import { padLeft, range } from 'lodash';
3030
import moment from 'moment-timezone';
3131
import React, { Component } from 'react';
3232
import styled from 'styled-components';
33-
import { LegacyCoreStart } from 'src/core/public';
3433
import { KibanaCoreContext } from '../../../../../../observability/public';
3534
import { IUrlParams } from '../../../../context/UrlParamsContext/types';
3635
import { KibanaLink } from '../../../shared/Links/KibanaLink';
@@ -39,12 +38,6 @@ import { ElasticDocsLink } from '../../../shared/Links/ElasticDocsLink';
3938

4039
type ScheduleKey = keyof Schedule;
4140

42-
const getUserTimezone = memoize((core: LegacyCoreStart): string => {
43-
return core.uiSettings.get('dateFormat:tz') === 'Browser'
44-
? moment.tz.guess()
45-
: core.uiSettings.get('dateFormat:tz');
46-
});
47-
4841
const SmallInput = styled.div`
4942
.euiFormRow {
5043
max-width: 85px;
@@ -284,17 +277,13 @@ export class WatcherFlyout extends Component<
284277
return null;
285278
}
286279

287-
const core = this.context;
288-
const userTimezoneSetting = getUserTimezone(core);
289280
const dailyTime = this.state.daily;
290281
const inputTime = `${dailyTime}Z`; // Add tz to make into UTC
291282
const inputFormat = 'HH:mmZ'; // Parse as 24 hour w. tz
292-
const dailyTimeFormatted = moment(inputTime, inputFormat)
293-
.tz(userTimezoneSetting)
294-
.format('HH:mm'); // Format as 24h
295-
const dailyTime12HourFormatted = moment(inputTime, inputFormat)
296-
.tz(userTimezoneSetting)
297-
.format('hh:mm A (z)'); // Format as 12h w. tz
283+
const dailyTimeFormatted = moment(inputTime, inputFormat).format('HH:mm'); // Format as 24h
284+
const dailyTime12HourFormatted = moment(inputTime, inputFormat).format(
285+
'hh:mm A (z)'
286+
); // Format as 12h w. tz
298287

299288
// Generate UTC hours for Daily Report select field
300289
const intervalHours = range(24).map(i => {

‎x-pack/legacy/plugins/apm/public/components/shared/TimestampTooltip/index.test.tsx‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,16 @@ describe('TimestampTooltip', () => {
1717
// mock Date.now
1818
mockNow(1570737000000);
1919

20-
// hardcode timezone to avoid timezone issues on CI
21-
jest
22-
.spyOn(moment.tz, 'guess')
23-
.mockImplementation(() => 'Europe/Copenhagen');
20+
moment.tz.setDefault('Etc/GMT');
2421
});
2522

23+
afterAll(() => moment.tz.setDefault(''));
24+
2625
it('should render component with relative time in body and absolute time in tooltip', () => {
2726
expect(shallow(<TimestampTooltip time={timestamp} />))
2827
.toMatchInlineSnapshot(`
2928
<EuiToolTip
30-
content="Oct 10th 2019, 17:06:40.123 (+0200 CEST)"
29+
content="Oct 10th 2019, 15:06:40.123 (+0000 GMT)"
3130
delay="regular"
3231
position="top"
3332
>
@@ -41,22 +40,22 @@ describe('TimestampTooltip', () => {
4140
shallow(<TimestampTooltip time={timestamp} />)
4241
.find('EuiToolTip')
4342
.prop('content')
44-
).toBe('Oct 10th 2019, 17:06:40.123 (+0200 CEST)');
43+
).toBe('Oct 10th 2019, 15:06:40.123 (+0000 GMT)');
4544
});
4645

4746
it('should format with precision in minutes', () => {
4847
expect(
4948
shallow(<TimestampTooltip time={timestamp} precision="minutes" />)
5049
.find('EuiToolTip')
5150
.prop('content')
52-
).toBe('Oct 10th 2019, 17:06 (+0200 CEST)');
51+
).toBe('Oct 10th 2019, 15:06 (+0000 GMT)');
5352
});
5453

5554
it('should format with precision in days', () => {
5655
expect(
5756
shallow(<TimestampTooltip time={timestamp} precision="days" />)
5857
.find('EuiToolTip')
5958
.prop('content')
60-
).toBe('Oct 10th 2019 (+0200 CEST)');
59+
).toBe('Oct 10th 2019 (+0000 GMT)');
6160
});
6261
});

‎x-pack/legacy/plugins/apm/public/components/shared/TimestampTooltip/index.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function getPreciseTime(precision: Props['precision']) {
2727
}
2828

2929
export function TimestampTooltip({ time, precision = 'milliseconds' }: Props) {
30-
const momentTime = moment.tz(time, moment.tz.guess());
30+
const momentTime = moment(time);
3131
const relativeTimeLabel = momentTime.fromNow();
3232
const absoluteTimeLabel = momentTime.format(
3333
`MMM Do YYYY${getPreciseTime(precision)} (ZZ zz)`

‎x-pack/legacy/plugins/apm/public/components/shared/charts/CustomPlot/StaticPlot.js‎

Lines changed: 36 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@ import PropTypes from 'prop-types';
1717
import React, { PureComponent } from 'react';
1818
import { last } from 'lodash';
1919
import { rgba } from 'polished';
20+
import { scaleUtc } from 'd3-scale';
2021

2122
import StatusText from './StatusText';
2223
import { SharedPlot } from './plotUtils';
2324
import { i18n } from '@kbn/i18n';
2425
import { isValidCoordinateValue } from '../../../../utils/isValidCoordinateValue';
26+
import { getTimezoneOffsetInMs } from './getTimezoneOffsetInMs';
2527

2628
// undefined values are converted by react-vis into NaN when stacking
2729
// see https://github.com/uber/react-vis/issues/1214
@@ -42,7 +44,7 @@ class StaticPlot extends PureComponent {
4244
<LineSeries
4345
getNull={getNull}
4446
key={serie.title}
45-
xType="time"
47+
xType="time-utc"
4648
curve={'curveMonotoneX'}
4749
data={serie.data}
4850
color={serie.color}
@@ -54,7 +56,7 @@ class StaticPlot extends PureComponent {
5456
<AreaSeries
5557
getNull={getNull}
5658
key={serie.title}
57-
xType="time"
59+
xType="time-utc"
5860
curve={'curveMonotoneX'}
5961
data={serie.data}
6062
color={serie.color}
@@ -78,7 +80,7 @@ class StaticPlot extends PureComponent {
7880
<AreaSeries
7981
getNull={getNull}
8082
key={`${serie.title}-area`}
81-
xType="time"
83+
xType="time-utc"
8284
curve={'curveMonotoneX'}
8385
data={data}
8486
color={serie.color}
@@ -90,7 +92,7 @@ class StaticPlot extends PureComponent {
9092
<LineSeries
9193
getNull={getNull}
9294
key={`${serie.title}-line`}
93-
xType="time"
95+
xType="time-utc"
9496
curve={'curveMonotoneX'}
9597
data={data}
9698
color={serie.color}
@@ -113,7 +115,7 @@ class StaticPlot extends PureComponent {
113115
<VerticalRectSeries
114116
getNull={getNull}
115117
key={serie.title}
116-
xType="time"
118+
xType="time-utc"
117119
curve={'curveMonotoneX'}
118120
data={data}
119121
color={serie.color}
@@ -126,7 +128,7 @@ class StaticPlot extends PureComponent {
126128
<LineMarkSeries
127129
getNull={getNull}
128130
key={serie.title}
129-
xType="time"
131+
xType="time-utc"
130132
curve={'curveMonotoneX'}
131133
data={serie.data}
132134
color={serie.color}
@@ -138,24 +140,42 @@ class StaticPlot extends PureComponent {
138140
}
139141
}
140142

143+
/**
144+
* A tick format function that takes the timezone from Kibana's settings into
145+
* account. Used if no tickFormatX prop is supplied.
146+
*
147+
* This produces the same results as the built-in formatter from D3, which is
148+
* what react-vis uses, but shifts the timezone.
149+
*/
150+
tickFormatXTime = value => {
151+
const xDomain = this.props.plotValues.x.domain();
152+
153+
const time = value.getTime();
154+
155+
return scaleUtc()
156+
.domain(xDomain)
157+
.tickFormat()(new Date(time - getTimezoneOffsetInMs(time)));
158+
};
159+
141160
render() {
142-
const {
143-
width,
144-
series,
145-
tickFormatX,
146-
tickFormatY,
147-
plotValues,
148-
noHits
149-
} = this.props;
150-
const { yTickValues } = plotValues;
161+
const { width, series, tickFormatY, plotValues, noHits } = this.props;
162+
const { xTickValues, yTickValues } = plotValues;
151163

152164
// approximate number of x-axis ticks based on the width of the plot. There should by approx 1 tick per 100px
153165
// d3 will determine the exact number of ticks based on the selected range
154166
const xTickTotal = Math.floor(width / 100);
155167

168+
const tickFormatX = this.props.tickFormatX || this.tickFormatXTime;
169+
156170
return (
157171
<SharedPlot plotValues={plotValues}>
158-
<XAxis tickSize={0} tickTotal={xTickTotal} tickFormat={tickFormatX} />
172+
<XAxis
173+
type="time-utc"
174+
tickSize={0}
175+
tickTotal={xTickTotal}
176+
tickFormat={tickFormatX}
177+
tickValues={xTickValues}
178+
/>
159179
{noHits ? (
160180
<StatusText
161181
marginLeft={30}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
import { getTimezoneOffsetInMs } from './getTimezoneOffsetInMs';
8+
import moment from 'moment-timezone';
9+
10+
describe('getTimezoneOffsetInMs', () => {
11+
describe('when no default timezone is set', () => {
12+
it('guesses the timezone', () => {
13+
const guess = jest.fn(() => 'Etc/UTC');
14+
jest.spyOn(moment.tz, 'guess').mockImplementationOnce(guess);
15+
16+
getTimezoneOffsetInMs(Date.now());
17+
18+
expect(guess).toHaveBeenCalled();
19+
});
20+
});
21+
22+
describe('when a default timezone is set', () => {
23+
let originalTimezone: moment.MomentZone | null;
24+
25+
beforeAll(() => {
26+
// @ts-ignore moment types do not define defaultZone but it's there
27+
originalTimezone = moment.defaultZone;
28+
moment.tz.setDefault('America/Denver');
29+
});
30+
31+
afterAll(() => {
32+
moment.tz.setDefault(originalTimezone ? originalTimezone.name : '');
33+
});
34+
35+
it('returns the time in milliseconds', () => {
36+
expect(getTimezoneOffsetInMs(Date.now())).toEqual(21600000);
37+
});
38+
});
39+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
import moment from 'moment-timezone';
7+
8+
export function getTimezoneOffsetInMs(time: number) {
9+
// @ts-ignore moment types don't define defaultZone but it's there
10+
const zone = moment.defaultZone ? moment.defaultZone.name : moment.tz.guess();
11+
12+
// @ts-ignore
13+
return moment.tz.zone(zone).parse(time) * 60000;
14+
}

‎x-pack/legacy/plugins/apm/public/components/shared/charts/CustomPlot/plotUtils.js‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import PropTypes from 'prop-types';
1212
import React from 'react';
1313

1414
import { unit } from '../../../../style/variables';
15+
import { getTimezoneOffsetInMs } from './getTimezoneOffsetInMs';
1516

1617
const XY_HEIGHT = unit * 16;
1718
const XY_MARGIN = {
@@ -64,15 +65,30 @@ export function getPlotValues(
6465
yMin = d3.min(flattenedCoordinates, d => d.y);
6566
}
6667

68+
const [xMinZone, xMaxZone] = [xMin, xMax].map(x => {
69+
return x - getTimezoneOffsetInMs(x);
70+
});
71+
6772
const xScale = getXScale(xMin, xMax, width);
6873
const yScale = getYScale(yMin, yMax);
6974

7075
const yMaxNice = yScale.domain()[1];
7176
const yTickValues = [0, yMaxNice / 2, yMaxNice];
7277

78+
const xTickValues = d3.time.scale
79+
.utc()
80+
.domain([xMinZone, xMaxZone])
81+
.range([0, width])
82+
.ticks()
83+
.map(x => {
84+
const time = x.getTime();
85+
return new Date(time + getTimezoneOffsetInMs(time));
86+
});
87+
7388
return {
7489
x: xScale,
7590
y: yScale,
91+
xTickValues,
7692
yTickValues,
7793
XY_MARGIN,
7894
XY_HEIGHT: height || XY_HEIGHT,
@@ -90,7 +106,7 @@ export function SharedPlot({ plotValues, ...props }) {
90106
dontCheckIfEmpty
91107
height={height}
92108
margin={margin}
93-
xType="time"
109+
xType="time-utc"
94110
width={width}
95111
xDomain={plotValues.x.domain()}
96112
yDomain={plotValues.y.domain()}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
// @ts-ignore
8+
import * as plotUtils from './plotUtils';
9+
10+
describe('plotUtils', () => {
11+
describe('getPlotValues', () => {
12+
describe('with empty arguments', () => {
13+
it('returns plotvalues', () => {
14+
expect(
15+
plotUtils.getPlotValues([], [], { height: 1, width: 1 })
16+
).toMatchObject({
17+
XY_HEIGHT: 1,
18+
XY_WIDTH: 1
19+
});
20+
});
21+
});
22+
23+
describe('when yMin is given', () => {
24+
it('uses the yMin in the scale', () => {
25+
expect(
26+
plotUtils
27+
.getPlotValues([], [], { height: 1, width: 1, yMin: 100 })
28+
.y.domain()[0]
29+
).toEqual(100);
30+
});
31+
32+
describe('when yMin is "min"', () => {
33+
it('uses minimum y from the series', () => {
34+
expect(
35+
plotUtils
36+
.getPlotValues(
37+
[{ data: { x: 0, y: 200 } }, { data: { x: 0, y: 300 } }],
38+
[],
39+
{
40+
height: 1,
41+
width: 1,
42+
yMin: 'min'
43+
}
44+
)
45+
.y.domain()[0]
46+
).toEqual(200);
47+
});
48+
});
49+
});
50+
51+
describe('when yMax given', () => {
52+
it('uses yMax', () => {
53+
expect(
54+
plotUtils
55+
.getPlotValues([], [], {
56+
height: 1,
57+
width: 1,
58+
yMax: 500
59+
})
60+
.y.domain()[1]
61+
).toEqual(500);
62+
});
63+
});
64+
});
65+
});

0 commit comments

Comments
 (0)