Skip to content

Commit

Permalink
Fixed time difference calculation in DST timezones
Browse files Browse the repository at this point in the history
refs https://github.com/TryGhost/Team/issues/588

- date-fns proved to be unable to manipulate dates consistently in UTC timezone. Keeping all calculations and formatting in UTC is key to have consistency in dates when dealing in inter-system dates
- day.js also failed the test for correct UTC manipulation. See iamkun/dayjs#1271 for example bug which prevents from consistent correct calculation
- luxon was the best option which WORKED. It's also a recommended successor for moment.js with really nice docs and active support
  • Loading branch information
naz committed May 7, 2021
1 parent 16e2123 commit 6a1e722
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
14 changes: 7 additions & 7 deletions ghost/limit-service/lib/date-utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
const differenceInMonths = require('date-fns/differenceInMonths');
const parseISO = require('date-fns/parseISO');
const addMonths = require('date-fns/addMonths');
const {DateTime} = require('luxon');

const SUPPORTED_INTERVALS = ['month'];
/**
Expand All @@ -14,11 +12,13 @@ const SUPPORTED_INTERVALS = ['month'];
*/
const lastPeriodStart = (startDate, interval) => {
if (interval === 'month') {
const startDateISO = parseISO(startDate);
const fullPeriodsPast = differenceInMonths(new Date(), startDateISO);
const lastPeriodStartDate = addMonths(startDateISO, fullPeriodsPast);
const startDateISO = DateTime.fromISO(startDate, {zone: 'UTC'});
const now = DateTime.now().setZone('UTC');
const fullPeriodsPast = Math.floor(now.diff(startDateISO, 'months').months);

return lastPeriodStartDate.toISOString();
const lastPeriodStartDate = startDateISO.plus({months: fullPeriodsPast});

return lastPeriodStartDate.toISO();
}

throw new Error('Invalid interval specified. Only "month" value is accepted.');
Expand Down
3 changes: 2 additions & 1 deletion ghost/limit-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"sinon": "10.0.0"
},
"dependencies": {
"lodash": "^4.17.21"
"lodash": "^4.17.21",
"luxon": "^1.26.0"
}
}

0 comments on commit 6a1e722

Please sign in to comment.