Skip to content

Instantly share code, notes, and snippets.

@daicorrea-tw
Forked from carlosmaniero/usage-interval.js
Created October 6, 2021 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save daicorrea-tw/38cd92799171d6d1b8c22e5a8b01716e to your computer and use it in GitHub Desktop.
Save daicorrea-tw/38cd92799171d6d1b8c22e5a8b01716e to your computer and use it in GitHub Desktop.
const toUnixTime = (date) => date.getTime() / 1000;
const usageInterval = (start, end) => ({
start: toUnixTime(start),
end: toUnixTime(end)
});
const getSyndayOfTheWeek = (currentDate) => {
const date = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
const today = date.getDate();
const dayOfTheWeek = date.getDay();
const newDate = date.setDate(today - (dayOfTheWeek || 7));
return new Date(newDate);
}
const usageIntervalFromPreviousWeek = (today = new Date()) => {
let currentWeekSunday = getSyndayOfTheWeek(today);
let previousWeekSunday = new Date(currentWeekSunday);
previousWeekSunday.setDate(previousWeekSunday.getDate() - 7);
return usageInterval(previousWeekSunday, currentWeekSunday);
}
module.exports = {
usageInterval,
usageIntervalFromPreviousWeek
}
const {usageIntervalFromPreviousWeek} = require("./usage-interval");
describe("usage-interval", () => {
it("should return the current week start as interval ending", () => {
const date = new Date(2021, 8, 25, 10, 15); // 2021-09-25
expect(usageIntervalFromPreviousWeek(date).end)
.toBe(new Date(2021, 8, 19).getTime() / 1000); // 2021-09-19
});
it("should return the previews week start as interval start", () => {
const date = new Date(2021, 8, 25, 10, 15); // 2021-09-25
expect(usageIntervalFromPreviousWeek(date).start)
.toBe(new Date(2021, 8, 12).getTime() / 1000); // 2021-09-12
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment