1 | /**
|
2 | * current-week-number <https://github.com/datetime/current-week-number>
|
3 | *
|
4 | * Copyright (c) 2014-2015 Charlike Mike Reagent, contributors.
|
5 | * Released under the MIT license.
|
6 | */
|
7 |
|
8 | ;
|
9 |
|
10 | /**
|
11 | * Get week number of the current date/year or given valid `Date` string format
|
12 | *
|
13 | * **Example:**
|
14 | *
|
15 | * ```js
|
16 | * var currentWeekNumber = require('current-week-number');
|
17 | *
|
18 | * // june 27, 2014
|
19 | * currentWeekNumber();
|
20 | * //=> 26
|
21 | *
|
22 | * currentWeekNumber('March 24, 2015');
|
23 | * //=> 13
|
24 | *
|
25 | * currentWeekNumber(new Date('March 24, 2015'));
|
26 | * //=> 13
|
27 | *
|
28 | * currentWeekNumber('03/24/2016');
|
29 | * //=> 12, cuz' year is leap
|
30 | *
|
31 | * currentWeekNumber('August 07, 2015');
|
32 | * //=> 32
|
33 | *
|
34 | * currentWeekNumber(new Date('August 07, 2016'));
|
35 | * //=> 31
|
36 | *
|
37 | * currentWeekNumber('02/16/2015');
|
38 | * //=> 8
|
39 | * ```
|
40 | *
|
41 | * @name currentWeekNumber
|
42 | * @param {String} `[date]` every valid Date-ish string format
|
43 | * @return {Number}
|
44 | * @api public
|
45 | */
|
46 | module.exports = function currentWeekNumber(date) {
|
47 | var instance;
|
48 |
|
49 | if (typeof date === 'string' && date.length) {
|
50 | instance = new Date(date);
|
51 | } else if (date instanceof Date) {
|
52 | instance = date;
|
53 | } else {
|
54 | instance = new Date();
|
55 | }
|
56 |
|
57 | // Create a copy of this date object
|
58 | var target = new Date(instance.valueOf());
|
59 |
|
60 | // ISO week date weeks start on monday
|
61 | // so correct the day number
|
62 | var dayNr = (instance.getDay() + 6) % 7;
|
63 |
|
64 | // ISO 8601 states that week 1 is the week
|
65 | // with the first thursday of that year.
|
66 | // Set the target date to the thursday in the target week
|
67 | target.setDate(target.getDate() - dayNr + 3);
|
68 |
|
69 | // Store the millisecond value of the target date
|
70 | var firstThursday = target.valueOf();
|
71 |
|
72 | // Set the target to the first thursday of the year
|
73 | // First set the target to january first
|
74 | target.setMonth(0, 1);
|
75 | // Not a thursday? Correct the date to the next thursday
|
76 | if (target.getDay() !== 4) {
|
77 | target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
|
78 | }
|
79 |
|
80 | // The weeknumber is the number of weeks between the
|
81 | // first thursday of the year and the thursday in the target week
|
82 | var weekNumber = 1 + Math.ceil((firstThursday - target) / 604800000);
|
83 | return weekNumber;
|
84 | };
|