-
Notifications
You must be signed in to change notification settings - Fork 0
/
datetime.js
414 lines (383 loc) · 11.8 KB
/
datetime.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/**
* @typedef {'seconds'|'minutes'|'hours'|'date'|'month'|'year'} Unit
*/
/**
* For the most part this object behaves exactly the same way
* as the native Date object with a little extra spice.
*/
export default class DateTime extends Date {
/**
* Used with Intl.DateTimeFormat
* @type {string}
*/
locale = "default";
/**
* Chainable way to set the {@link locale}
* @param value
* @returns {DateTime}
*/
setLocale(value) {
this.locale = value;
return this;
}
/**
* Converts a plain JS date object to a DateTime object.
* Doing this allows access to format, etc.
* @param {Date|DateTime} date
* @returns {DateTime}
*/
static convert(date) {
if (!date) throw `A date is required`;
if (typeof date.startOf === "function") return date;
if (typeof date.getDate !== "function") throw `A date is required`;
return new DateTime(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
/**
* Native date manipulations are not pure functions. This function creates a duplicate of the DateTime object.
* @returns {DateTime}
*/
get clone() {
return new DateTime(
this.year,
this.month,
this.date,
this.hours,
this.minutes,
this.seconds,
this.getMilliseconds()
).setLocale(this.locale);
}
/**
* Sets the current date to the start of the {@link unit} provided
* Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).startOf('month')
* would return April 1, 2021, 12:00:00.000 AM (midnight)
* @param {Unit|'weekDay'} unit
* @returns {DateTime} self
*/
startOf(unit) {
if (this[unit] === undefined) throw `Unit '${unit}' is not valid`;
switch (unit) {
case "seconds":
this.setMilliseconds(0);
break;
case "minutes":
this.setSeconds(0, 0);
break;
case "hours":
this.setMinutes(0, 0, 0);
break;
case "date":
this.setHours(0, 0, 0, 0);
break;
case "weekDay":
this.startOf("date");
this.manipulate(0 - this.weekDay, "date");
break;
case "month":
this.startOf("date");
this.setDate(1);
break;
case "year":
this.startOf("date");
this.setMonth(0, 1);
break;
}
return this;
}
/**
* Sets the current date to the end of the {@link unit} provided
* Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).endOf('month')
* would return April 30, 2021, 11:59:59.999 PM
* @param {Unit|'weekDay'} unit
* @returns {DateTime} self
*/
endOf(unit) {
if (this[unit] === undefined) throw `Unit '${unit}' is not valid`;
switch (unit) {
case "seconds":
this.setMilliseconds(999);
break;
case "minutes":
this.setSeconds(59, 999);
break;
case "hours":
this.setMinutes(59, 59, 999);
break;
case "date":
this.setHours(23, 59, 59, 999);
break;
case "weekDay":
this.startOf("date");
this.manipulate(6 - this.weekDay, "date");
break;
case "month":
this.endOf("date");
this.manipulate(1, "month");
this.setDate(0);
break;
case "year":
this.endOf("date");
this.manipulate(1, "year");
this.setDate(0);
break;
}
return this;
}
/**
* Change a {@link unit} value. Value can be positive or negative
* Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).manipulate(1, 'month')
* would return May 30, 2021, 11:45:32.984 AM
* @param value A positive or negative number
* @param {Unit} unit
* @returns {DateTime}
*/
manipulate(value, unit) {
if (this[unit] === undefined) throw `Unit '${unit}' is not valid`;
this[unit] += value;
return this;
}
/**
* Returns a string format.
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
* for valid templates and locale objects
* @param {Object} template An object. Uses browser defaults otherwise.
* @param {string} locale Can be a string or an array of strings. Uses browser defaults otherwise.
* @returns {string}
*/
format(template, locale = this.locale) {
return new Intl.DateTimeFormat(locale, template).format(this);
}
/**
* Return true if {@link compare} is before this date
* @param {Date|DateTime} compare The Date/DateTime to compare
* @param {Unit?} unit. If provided, uses {@link startOf} for
* comparision.
* @returns {boolean}
*/
isBefore(compare, unit) {
if (!unit) return this < compare;
if (this[unit] === undefined) throw `Unit '${unit}' is not valid`;
compare = DateTime.convert(compare);
return (
this.clone.startOf(unit).valueOf() < compare.clone.startOf(unit).valueOf()
);
}
/**
* Return true if {@link compare} is after this date
* @param {Date|DateTime} compare The Date/DateTime to compare
* @param {Unit?} unit. If provided, uses {@link startOf} for
* comparision.
* @returns {boolean}
*/
isAfter(compare, unit) {
if (!unit) return this > compare;
if (this[unit] === undefined) throw `Unit '${unit}' is not valid`;
compare = DateTime.convert(compare);
return (
this.clone.startOf(unit).valueOf() > compare.clone.startOf(unit).valueOf()
);
}
/**
* Return true if {@link compare} is same this date
* @param {Date|DateTime} compare The Date/DateTime to compare
* @param {Unit?} unit. If provided, uses {@link startOf} for
* comparision.
* @returns {boolean}
*/
isSame(compare, unit) {
if (!unit) return this.valueOf() === compare.valueOf();
if (this[unit] === undefined) throw `Unit '${unit}' is not valid`;
compare = DateTime.convert(compare);
return (
this.clone.startOf(unit).valueOf() === compare.startOf(unit).valueOf()
);
}
/**
* Check if this is between two other DateTimes, optionally looking at unit scale. The match is exclusive.
* @param {Date|DateTime} left
* @param {Date|DateTime} right
* @param {Unit} unit.
* @param {string} inclusivity. A [ indicates inclusion of a value. A ( indicates exclusion.
* If the inclusivity parameter is used, both indicators must be passed.
* @returns {boolean}
*/
isBetween(left, right, unit, inclusivity = "()") {
if (this[unit] === undefined) throw `Unit '${unit}' is not valid`;
const leftInclusivity = inclusivity[0] === "(";
const rightInclusivity = inclusivity[1] === ")";
left = DateTime.convert(left);
right = DateTime.convert(right);
return (
((leftInclusivity
? this.isAfter(left, unit)
: !this.isBefore(left, unit)) &&
(rightInclusivity
? this.isBefore(right, unit)
: !this.isAfter(right, unit))) ||
((leftInclusivity
? this.isBefore(left, unit)
: !this.isAfter(left, unit)) &&
(rightInclusivity
? this.isAfter(right, unit)
: !this.isBefore(right, unit)))
);
}
/**
* Returns flattened object of the date. Does not include literals
* @param {string} locale
* @param {Object} template
* @returns {{}}
*/
parts(
locale = this.locale,
template = { dateStyle: "full", timeStyle: "long" }
) {
const parts = {};
new Intl.DateTimeFormat(locale, template)
.formatToParts(this)
.filter(x => x.type !== "literal")
.forEach(x => (parts[x.type] = x.value));
return parts;
}
/**
* Shortcut to Date.getSeconds()
* @returns {number}
*/
get seconds() {
return this.getSeconds();
}
/**
* Shortcut to Date.setSeconds()
*/
set seconds(value) {
this.setSeconds(value);
}
/**
* Shortcut to Date.getMinutes()
* @returns {number}
*/
get minutes() {
return this.getMinutes();
}
/**
* Shortcut to Date.setMinutes()
*/
set minutes(value) {
this.setMinutes(value);
}
/**
* Shortcut to Date.getHours()
* @returns {number}
*/
get hours() {
return this.getHours();
}
/**
* Shortcut to Date.setHours()
*/
set hours(value) {
this.setHours(value);
}
/**
* Get the meridiem of the date. E.g. AM or PM.
* If the {@link locale} provides a "dayPeriod" then this will be returned,
* otherwise it will return AM or PM.
* @param locale
* @returns {string}
*/
meridiem(locale = this.locale) {
const dayPeriod = new Intl.DateTimeFormat(locale, {
hour: "numeric",
dayPeriod: "narrow"
})
.formatToParts(this)
.find(p => p.type === "dayPeriod")?.value;
return dayPeriod ? dayPeriod : this.getHours() <= 12 ? "AM" : "PM";
}
/**
* Shortcut to Date.getDate()
* @returns {number}
*/
get date() {
return this.getDate();
}
/**
* Shortcut to Date.setDate()
*/
set date(value) {
this.setDate(value);
}
/**
* Return two digit date
* @returns {string}
*/
get dateFormatted() {
return this.date < 10 ? `0${this.date}` : `${this.date}`;
}
// https://github.com/you-dont-need/You-Dont-Need-Momentjs#week-of-year
/**
* Gets the week of the year
* @returns {number}
*/
get week() {
const MILLISECONDS_IN_WEEK = 604800000;
const firstDayOfWeek = 1; // monday as the first day (0 = sunday)
const startOfYear = new Date(this.year, 0, 1);
startOfYear.setDate(
startOfYear.getDate() + (firstDayOfWeek - (startOfYear.getDay() % 7))
);
return (
Math.round(
(this.valueOf() - startOfYear.valueOf()) / MILLISECONDS_IN_WEEK
) + 1
);
}
/**
* Shortcut to Date.getDay()
* @returns {number}
*/
get weekDay() {
return this.getDay();
}
/**
* Shortcut to Date.getMonth()
* @returns {number}
*/
get month() {
return this.getMonth();
}
/**
* Shortcut to Date.setMonth()
*/
set month(value) {
this.setMonth(value);
}
/**
* Return two digit, human expected month. E.g. January = 1, December = 12
* @returns {string}
*/
get monthFormatted() {
return this.month + 1 < 10 ? `0${this.month}` : `${this.month}`;
}
/**
* Shortcut to Date.getFullYear()
* @returns {number}
*/
get year() {
return this.getFullYear();
}
/**
* Shortcut to Date.setFullYear()
*/
set year(value) {
this.setFullYear(value);
}
}