Ghost/ghost/limit-service/lib/date-utils.js
Naz 6a1e722648 Fixed time difference calculation in DST timezones
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 https://github.com/iamkun/dayjs/issues/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
2021-05-07 14:41:52 +04:00

31 lines
1.1 KiB
JavaScript

const {DateTime} = require('luxon');
const SUPPORTED_INTERVALS = ['month'];
/**
* Calculates the start of the last period (billing, cycle, etc.) based on the start date
* and the interval at which the cycle renews.
*
* @param {String} startDate - date in ISO 8601 format (https://en.wikipedia.org/wiki/ISO_8601)
* @param {('month')} interval - currently only supports 'month' value, in the future might support 'year', etc.
*
* @returns {String} - date in ISO 8601 format (https://en.wikipedia.org/wiki/ISO_8601) of the last period start
*/
const lastPeriodStart = (startDate, interval) => {
if (interval === 'month') {
const startDateISO = DateTime.fromISO(startDate, {zone: 'UTC'});
const now = DateTime.now().setZone('UTC');
const fullPeriodsPast = Math.floor(now.diff(startDateISO, 'months').months);
const lastPeriodStartDate = startDateISO.plus({months: fullPeriodsPast});
return lastPeriodStartDate.toISO();
}
throw new Error('Invalid interval specified. Only "month" value is accepted.');
};
module.exports = {
lastPeriodStart,
SUPPORTED_INTERVALS
};