-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmoment.isocalendar.js
More file actions
100 lines (83 loc) · 2.22 KB
/
Copy pathmoment.isocalendar.js
File metadata and controls
100 lines (83 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
if ( typeof require !== 'undefined' )
{
moment = require('moment');
}
;(function(moment) {
var firstIsoWeekOfYear = function(year) {
var m = moment([year])
, day = m.day();
if ( day === 0 )
{
day = 7;
}
// ISO week is the first week with a Thursday, so if the first
// day of the year is Friday, move to next Sunday.
if ( day > 4 ) {
m.add('weeks', 1);
}
m.subtract('days', day - 1);
return m;
}
// 0 => year, 1 => week, 2 => day, 3 => minute
, index_method_map = ['year', 'week', 'day', 'minute']
// This method powers the getter/setter methods
, genericAccessor = function(index, value) {
if ( value )
{
var iso = this.isocalendar();
iso[index] = value;
this._d = moment.fromIsocalendar(iso).toDate();
return this;
}
else
{
return this.isocalendar()[index];
}
}
// Helper method for tying together the getter/setters.
, accessorFactory = function(index) {
return function(value) {
return genericAccessor.call(this, index, value);
};
}
;
moment.fn.isocalendar = function() {
var year = this.year()
, firstMonday = firstIsoWeekOfYear(year)
, week = Math.floor(this.diff(firstMonday, 'weeks', true)) + 1
, day = this.day()
, minute = this.hours() * 60 + this.minutes()
;
if ( week == 53 && firstIsoWeekOfYear(year + 1) <= this )
{
year += 1;
week = 1;
}
else if ( week < 1 )
{
year -= 1;
week = moment([year, 11, 31, 0, 0]).isocalendar()[1];
}
if ( day === 0 )
{
day = 7;
}
return [ year
, week
, day
, minute
];
};
moment.fromIsocalendar = function(array) {
var date = firstIsoWeekOfYear(array[0]).add({
weeks: array[1] - 1
, days: array[2] - 1
, minutes: array[3]
});
return date;
};
// isoyear, isomonth, isoday, isominute setters.
for (var i = 0, _len = index_method_map.length; i < _len; i++) {
moment.fn['iso' + index_method_map[i]] = accessorFactory(i);
}
})(moment);