Skip to content

Commit

Permalink
Chart: Fix timezone issues (#2203)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre-Gilles authored Jan 23, 2025
1 parent 04c1528 commit 6829fac
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
5 changes: 3 additions & 2 deletions server/lib/device/device.getDeviceFeaturesAggregates.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ async function getDeviceFeaturesAggregates(selector, intervalInMinutes, maxState

const isBinary = ['binary', 'push'].includes(deviceFeature.type);

const now = new Date();
const intervalDate = new Date(now.getTime() - intervalInMinutes * 60 * 1000);
// Get the interval date, and offset in UTC
const intervalDate = new Date(Date.now() - intervalInMinutes * 60 * 1000);
intervalDate.setMinutes(intervalDate.getMinutes() - intervalDate.getTimezoneOffset());

let values;

Expand Down
29 changes: 29 additions & 0 deletions server/test/lib/device/device.getDeviceFeaturesAggregates.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@ const EventEmitter = require('events');
const { expect, assert } = require('chai');
const sinon = require('sinon');
const { fake } = require('sinon');
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');

const db = require('../../../models');
const Device = require('../../../lib/device');
const Job = require('../../../lib/job');

const event = new EventEmitter();
const job = new Job(event);

// Extend Day.js with plugins
dayjs.extend(utc);
dayjs.extend(timezone);

const insertStates = async (intervalInMinutes) => {
const deviceFeatureStateToInsert = [];
const now = new Date();
Expand Down Expand Up @@ -95,6 +103,27 @@ describe('Device.getDeviceFeaturesAggregates non binary feature', function Descr
expect(device).to.have.property('name');
expect(deviceFeature).to.have.property('name');
});
it('should test timezone behavior', async () => {
// Create current date in Toronto timezone, 30 minutes ago
const torontoDate = dayjs()
.tz('America/Toronto')
.subtract(30, 'minute')
.toDate();

await db.duckDbInsertState('ca91dfdf-55b2-4cf8-a58b-99c0fbf6f5e4', 1, torontoDate);
const variable = {
getValue: fake.resolves(null),
};
const stateManager = {
get: fake.returns({
id: 'ca91dfdf-55b2-4cf8-a58b-99c0fbf6f5e4',
name: 'my-feature',
}),
};
const deviceInstance = new Device(event, {}, stateManager, {}, {}, variable, job);
const { values } = await deviceInstance.getDeviceFeaturesAggregates('test-device-feature', 60, 100);
expect(values).to.have.lengthOf(1);
});
it('should return last day states', async () => {
await insertStates(48 * 60);
const variable = {
Expand Down

0 comments on commit 6829fac

Please sign in to comment.