-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIPeriod.js
executable file
·307 lines (252 loc) · 9.59 KB
/
IPeriod.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
(function (root) {
"use strict";
/**
* need: IDate, jQuery
* @args:
* [IPeriod]
* [startDate, days]
* ["12.01.2012 - today"]
* [startDate, endDate]
* [startDate]
* [days]
**/
var IPeriod = function () {
this.attributes = {
start: new IDate('today'),
end: new IDate('today')
};
var args = arguments;
/**
* Если не указаны аргументы, то содаем период по-умолчанию
*/
if (args.length == 0 || (args.length == 1 && !args[0])) {
return this;
}
/**
*
*/
if (args[0] instanceof IPeriod) {
this.attributes.start = new IDate(args[0].attributes.start);
this.attributes.end = new IDate(args[0].attributes.end);
} else if (args.length == 2 && typeof args[1] === 'number') {
// установим начальную дату из первого аргумента
this.attributes.start = new IDate(args[0]);
// конечная = начальная + указанное кол-во дней
this.attributes.end = this.attributes.start.getShifted({days: args[1]});
} else {
/**
* ["12.01.2012 - 24.02.2012"]
* ["12.01.2012 - today"]
* ["12.01.2012"]
*/
if (args.length == 1 && typeof args[0] === 'string' && args[0].replace(/[^0-9a-z]/ig, '').length > 0) {
var periodArr = args[0].replace(/\s*/g, '').split(this.separator);
this.attributes.start = new IDate(periodArr[0]);
this.attributes.end = new IDate(periodArr[1] || 'today');
} else {
if (typeof args[0] === 'string' || (typeof args[0] === 'object' && !(args[0] instanceof Array))) {
this.attributes.start = new IDate(args[0]);
this.attributes.end = new IDate(args[1] || 'today');
} else if (args.length == 1 && typeof args[0] === 'number') {
this.attributes.start = new IDate('today');
this.attributes.end = this.attributes.start.getShifted({
days: args[0]
});
}
}
}
// начальная больше конечной - перевернем
if (this.getUnitDifference('days') < 0) {
this.reverse();
}
return this;
};
IPeriod.prototype = {
separator: '-',
dateFormat: 'dd.mm.yyyy',
/**
* Меняет местами дату начала и конца периода
* @private
*/
reverse: function () {
var tmp = this.attributes.end;
this.attributes.end = this.attributes.start;
this.attributes.start = tmp;
return this;
},
/**
* @description Возвращает разницу дат в периоде, end - start,
* {years, months, days, hours, minutes, seconds, ms}
* @returns {*}
*/
getDifference: function () {
return this.attributes.end.getDifference(this.attributes.start);
},
/**
* Возвращает разницу дат в периоде в указанных едтиницах
* @param units
* @returns {*}
*/
getUnitDifference: function (units) {
if (units == null) {
units = 'days';
}
return this.attributes.end.getUnitDifference(this.attributes.start, units);
},
/**
* @description проверка на валидность периода. Если указать количество дней, то выполнится проверка на количество дней в периоде
* @param days
* @returns {boolean}
*/
validate: function (days) {
if (!this.attributes.start.validate(this.dateFormat) || !this.attributes.end.validate(this.dateFormat)) {
return false;
}
if (typeof days === 'number') {
if (this.attributes.start.getUnitDifference(this.attributes.end, 'days') != days) {
return false;
}
}
return true;
},
/**
*
* @param dateFormat
* @param separator
* @returns {string}
*/
toString: function (dateFormat, separator) {
if (typeof dateFormat !== "string") {
dateFormat = this.dateFormat;
}
if (typeof separator !== "string") {
separator = this.separator;
}
return this.attributes.start.toString(dateFormat) + separator + this.attributes.end.toString(dateFormat);
},
/**
*
* @returns {string}
*/
toHtml: function () {
return "<span>" + this.toString.apply(this, arguments) + "</span>";
},
/**
* @description возвращает период в 1 месяц.
* @param type null || "start" - месяц начальной даты, "end" - месяц конечной даты
* @returns {IPeriod}
*/
getMonthPeriod: function (type) {
var period = new IPeriod(this);
if (typeof type !== "string" || type.toLowerCase() == "start") {
period.attributes.start.set('date', 1);
period.attributes.end = period.attributes.start.getShifted({days: period.attributes.start.getDaysInMonth() - 1});
} else {
period.attributes.start.set('date', 1);
period.attributes.end = period.attributes.end.getShifted({days: period.attributes.end.getDaysInMonth() - 1});
}
return period;
},
/**
* @description Добавляет к периоду указанное кол-во дней/месяцев.. = this + counts,
* counts = {years, months, days, hours, minutes, seconds, ms} || date(int)
* @param counts
* @returns {IPeriod}
*/
getShifted: function (counts) {
var period = new IPeriod(this);
period.attributes.start = period.attributes.start.getShifted(counts);
period.attributes.end = period.attributes.end.getShifted(counts);
return period;
},
/**
*
* @param period
* @returns {boolean|*|Boolean}
*/
is: function (period) {
var _period = new IPeriod(period);
return (
this.validate() && _period.validate()
) && (
this.attributes.end.is(_period.attributes.end, 'dd.mm.yyyy')
&& this.attributes.start.is(_period.attributes.start, 'dd.mm.yyyy')
);
},
/**
*
* @param attribute
* @returns {*}
*/
get: function (attribute) {
return this.attributes[attribute];
},
/**
*
* @param attribute
* @param value
*/
set: function (attribute, value) {
this.attributes[attribute] = value;
},
/**
* @description Количество дней в периоде
* @param options
* - isRounded - возвращать округлённое кол-во дней или нет
* @return {Number}
*/
getDaysCount: function (options) {
options = options || {};
return Math[options.isRounded ? 'round' : 'ceil'](
(
this.attributes.end.getMilliseconds() - this.attributes.start.getMilliseconds()
) / (1000 * 60 * 60 * 24)
);
},
/**
* период c начала текущего месяца по сегодня
* если сегодняшняя дата меньше 10, захватываем и предыдущий месяц
* @returns {IPeriod}
*/
getPeriodFromMonthStartToToday: function () {
return new IPeriod(
(new IDate('today')).get('date') > 10 ? new IDate({ days: 1 - (new IDate()).get('date') }) : (new IDate({months: -1})).set({date: 1}),
'today'
);
},
/**
*
* @returns {boolean}
*/
isMonthPeriod: function () {
return this.attributes.start.attributes.date.value === 1 && this.hasSameMonths() && this.hasSameYears() &&
this.getUnitDifference('days') === this.attributes.start.getDaysInMonth() - 1;
},
/**
*
* @returns {boolean}
*/
hasSameDates: function () {
return this.attributes.start.attributes.date.value === this.attributes.end.attributes.date.value;
},
/**
*
* @returns {boolean}
*/
hasSameMonths: function () {
return this.attributes.start.attributes.month.value === this.attributes.end.attributes.month.value;
},
/**
*
* @returns {boolean}
*/
hasSameYears: function () {
return this.attributes.start.attributes.year.value === this.attributes.end.attributes.year.value;
}
};
if (typeof module !== "undefined" && module.exports) {
module.exports = IPeriod;
} else {
root.IPeriod = IPeriod;
}
}(this));