Use dayjs's `utc` plugin in `startDaysBetween()`

This commit is contained in:
Kemal Zebari 2024-05-04 11:33:32 -07:00
parent 4c6b196902
commit 64dbabd15d
4 changed files with 19 additions and 15 deletions

View File

@ -67,7 +67,7 @@ export default {
const weekValues = Object.values(this.data);
const start = weekValues[0].week;
const end = firstStartDateAfterDate(new Date());
const startDays = startDaysBetween(new Date(start), new Date(end));
const startDays = startDaysBetween(start, end);
this.data = fillEmptyStartDaysWithZeroes(startDays, this.data);
this.errorText = '';
} else {

View File

@ -114,7 +114,7 @@ export default {
const weekValues = Object.values(total.weeks);
this.xAxisStart = weekValues[0].week;
this.xAxisEnd = firstStartDateAfterDate(new Date());
const startDays = startDaysBetween(new Date(this.xAxisStart), new Date(this.xAxisEnd));
const startDays = startDaysBetween(this.xAxisStart, this.xAxisEnd);
total.weeks = fillEmptyStartDaysWithZeroes(startDays, total.weeks);
this.xAxisMin = this.xAxisStart;
this.xAxisMax = this.xAxisEnd;

View File

@ -62,7 +62,7 @@ export default {
const data = await response.json();
const start = Object.values(data)[0].week;
const end = firstStartDateAfterDate(new Date());
const startDays = startDaysBetween(new Date(start), new Date(end));
const startDays = startDaysBetween(start, end);
this.data = fillEmptyStartDaysWithZeroes(startDays, data).slice(-52);
this.errorText = '';
} else {

View File

@ -1,25 +1,29 @@
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc.js';
import {getCurrentLocale} from '../utils.js';
// Returns an array of millisecond-timestamps of start-of-week days (Sundays)
export function startDaysBetween(startDate, endDate) {
dayjs.extend(utc);
/**
* Returns an array of millisecond-timestamps of start-of-week days (Sundays)
*
* @param startConfig can take any type that `Date` accepts.
* @param endConfig can take any type that `Date` accepts.
*/
export function startDaysBetween(startConfig, endConfig) {
const start = dayjs.utc(startConfig);
const end = dayjs.utc(endConfig);
// Ensure the start date is a Sunday
while (startDate.getUTCDay() !== 0) {
startDate.setUTCDate(startDate.getUTCDate() + 1);
while (start.day() !== 0) {
start.add(1, 'day');
}
const start = dayjs(startDate);
const end = dayjs(endDate);
const startDays = [];
let current = start;
while (current.isBefore(end)) {
startDays.push(current.valueOf());
// we are adding 7 * 24 hours instead of 1 week because we don't want
// date library to use local time zone to calculate 1 week from now.
// local time zone is problematic because of daylight saving time (dst)
// used on some countries
current = current.add(7 * 24, 'hour');
current = current.add(1, 'week');
}
return startDays;