Skip to content

Commit

Permalink
add timezone-safe week of epoch scope
Browse files Browse the repository at this point in the history
  • Loading branch information
smhg committed Nov 14, 2018
1 parent 49c9bd1 commit bf528d7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/util/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@

import { dayOfYear, weekNumber } from 'weeknumber';

const MINUTE = 60000;
const WEEK = 604800000;

const weekday = date => (date.getDay() + 6) % 7 + 1;

const weekEpoch = new Date(1970, 0, -2); // monday before unix epoch in local timezone
const weekOfEpoch = date =>
Math.abs(Math.floor((date - weekEpoch + (weekEpoch.getTimezoneOffset() - date.getTimezoneOffset()) * MINUTE) / WEEK));

function modify (date, unit, value) {
switch (unit) {
case 'Y':
Expand Down Expand Up @@ -48,6 +55,7 @@ const util = {
Y: date => date.getMonth() + 1
},
W: {
E: weekOfEpoch,
Y: weekNumber
},
D: {
Expand Down
1 change: 1 addition & 0 deletions test/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ describe('util', function () {
assert.strictEqual(util.date.get.D.W(new Date(2014, 1, 9)), 7);
assert.strictEqual(util.date.get.W.Y(new Date(2018, 6, 1)), 26);
assert.strictEqual(util.date.get.W.Y(new Date(2021, 0, 1)), 53);
assert.strictEqual(util.date.get.W.E(new Date(1970, 0, 1)), 0);
});
});
});
Expand Down

0 comments on commit bf528d7

Please sign in to comment.