@jsb188/app 1.0.3 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/utils/datetime.ts CHANGED
@@ -1,26 +1,45 @@
1
- import type { DatePeriodEnum } from '../types/datetime.d';
2
- import i18n from '../i18n/';
1
+ import i18n from '../i18n';
2
+ import { isValidTimeZone, parseDateInTimezone } from './timeZone';
3
3
 
4
4
  /**
5
5
  * Types
6
6
  */
7
7
 
8
+ export type DatePeriodEnum =
9
+ | 'UPCOMING'
10
+ | 'TOMORROW'
11
+ | 'TODAY'
12
+ | 'YESTERDAY'
13
+ | 'THIS_WEEK'
14
+ | 'THIS_MONTH'
15
+ | 'LAST_WEEK'
16
+ | 'LAST_MONTH'
17
+ | 'OLDER';
18
+
19
+ export interface DatePeriodObj {
20
+ datePeriod: DatePeriodEnum | string; // 'YYYY-MM-DD' (string) if groupByDate is true
21
+ date: Date;
22
+ item: any;
23
+ }
24
+
8
25
  interface TimeAgoParams {
9
- locales: string;
10
- justNowThresh: number
11
- nowThresh: number;
12
- disableFuture: boolean;
13
- isToday: boolean;
14
- skipTodayCheck: boolean;
26
+ locales: string;
27
+ justNowThresh: number;
28
+ nowThresh: number;
29
+ disableFuture: boolean;
30
+ isToday: boolean;
31
+ skipTodayCheck: boolean;
15
32
  }
16
33
 
17
34
  interface FullTimeParams {
18
- locales: string;
19
- hideYear: boolean;
20
- hideDate: boolean;
21
- hideTime: boolean;
22
- showTextDate: boolean;
23
- alwaysShowYear: boolean;
35
+ timeZone: string | null;
36
+ locales: string;
37
+ hideYear: boolean;
38
+ hideDate: boolean;
39
+ hideTime: boolean;
40
+ textDateStyle: 'long' | 'short' | null;
41
+ alwaysShowYear: boolean;
42
+ includeWeekday: boolean;
24
43
  }
25
44
 
26
45
  /**
@@ -28,7 +47,7 @@ interface FullTimeParams {
28
47
  */
29
48
 
30
49
  function getStartOfDay(date: Date) {
31
- return new Date(date.getFullYear(), date.getMonth(), date.getDate());
50
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate());
32
51
  }
33
52
 
34
53
  /**
@@ -36,7 +55,7 @@ function getStartOfDay(date: Date) {
36
55
  */
37
56
 
38
57
  function getDaysDiff(date1: Date, date2: Date) {
39
- return Math.floor((getStartOfDay(date1).getTime() - getStartOfDay(date2).getTime()) / (1000 * 60 * 60 * 24));
58
+ return Math.floor((getStartOfDay(date1).getTime() - getStartOfDay(date2).getTime()) / (1000 * 60 * 60 * 24));
40
59
  }
41
60
 
42
61
  /**
@@ -44,93 +63,170 @@ function getDaysDiff(date1: Date, date2: Date) {
44
63
  */
45
64
 
46
65
  export function getDatePeriod(d1: Date, d2: Date): DatePeriodEnum {
47
-
48
- const diffDays = getDaysDiff(d1, d2);
49
-
50
- switch (diffDays) {
51
- case 0:
52
- return 'TODAY';
53
- case 1:
54
- return 'TOMORROW';
55
- case -1:
56
- return 'YESTERDAY';
57
- case -7:
58
- return 'LAST_WEEK';
59
- case -30:
60
- return 'LAST_MONTH';
61
- default:
62
- if (diffDays > 1) {
63
- return 'UPCOMING';
64
- }
65
- }
66
-
67
- const diffInWeeks = Math.ceil(diffDays / 7);
68
- if (diffInWeeks === 0) {
69
- return 'THIS_WEEK';
70
- } else if (diffInWeeks === -1) {
71
- return 'LAST_WEEK';
72
- }
73
-
74
- const diffInMonths = (d2.getFullYear() - d1.getFullYear()) * 12 + (d2.getMonth() - d1.getMonth());
75
- if (diffInMonths === 0) {
76
- return 'THIS_MONTH';
77
- } else if (diffInMonths === -1) {
78
- return 'LAST_MONTH';
79
- }
80
-
81
- return 'OLDER';
66
+ const diffDays = getDaysDiff(d1, d2);
67
+
68
+ switch (diffDays) {
69
+ case 0:
70
+ return 'TODAY';
71
+ case 1:
72
+ return 'TOMORROW';
73
+ case -1:
74
+ return 'YESTERDAY';
75
+ case -7:
76
+ return 'LAST_WEEK';
77
+ case -30:
78
+ return 'LAST_MONTH';
79
+ default:
80
+ if (diffDays > 1) {
81
+ return 'UPCOMING';
82
+ }
83
+ }
84
+
85
+ const diffInWeeks = Math.ceil(diffDays / 7);
86
+ if (diffInWeeks === 0) {
87
+ return 'THIS_WEEK';
88
+ } else if (diffInWeeks === -1) {
89
+ return 'LAST_WEEK';
90
+ }
91
+
92
+ const diffInMonths = (d2.getFullYear() - d1.getFullYear()) * 12 + (d2.getMonth() - d1.getMonth());
93
+ if (diffInMonths === 0) {
94
+ return 'THIS_MONTH';
95
+ } else if (diffInMonths === -1) {
96
+ return 'LAST_MONTH';
97
+ }
98
+
99
+ return 'OLDER';
82
100
  }
83
101
 
84
102
  /**
85
103
  * Get full date with time
86
104
  */
87
105
 
88
- export function getFullTimeDate(
89
- _d: Date | string | number | null,
90
- params?: Partial<FullTimeParams>
106
+ export function getFullDateTime(
107
+ _d: Date | string | number | null,
108
+ params?: Partial<FullTimeParams>,
91
109
  ) {
110
+ const {
111
+ locales = 'en-US',
112
+ timeZone: timeZone_,
113
+ hideYear,
114
+ hideDate,
115
+ hideTime,
116
+ textDateStyle,
117
+ alwaysShowYear,
118
+ includeWeekday,
119
+ } = params || {};
120
+
121
+ let d;
122
+ if (_d instanceof Date) {
123
+ d = _d;
124
+ } else {
125
+ // Make sure _d is not null, before using this function
126
+ d = _d ? new Date(_d) : new Date(-1);
127
+ }
128
+
129
+ let timeZone = timeZone_ || undefined; // cannot be null, else it will throw error
130
+ if (timeZone && !isValidTimeZone(timeZone)) {
131
+ timeZone = undefined;
132
+ }
133
+
134
+ if (hideDate) {
135
+ return d.toLocaleTimeString(locales, {
136
+ timeZone,
137
+ hour: 'numeric',
138
+ minute: '2-digit',
139
+ });
140
+ }
141
+
142
+ // If year is same year, then don't show year
143
+ let hideYear_;
144
+ if (!hideYear && !alwaysShowYear) {
145
+ const dateYear = d.getFullYear();
146
+ const currentYear = new Date().getFullYear();
147
+ hideYear_ = dateYear === currentYear;
148
+ } else if (hideYear || hideDate) {
149
+ hideYear_ = true;
150
+ }
151
+
152
+ return d.toLocaleDateString(locales, {
153
+ timeZone,
154
+ day: 'numeric',
155
+ weekday: includeWeekday && textDateStyle === 'long' ? 'long' : includeWeekday ? 'short' : undefined,
156
+ month: textDateStyle || 'numeric',
157
+ year: hideYear_ ? undefined : 'numeric',
158
+ hour: hideTime ? undefined : 'numeric',
159
+ minute: hideTime ? undefined : '2-digit',
160
+ });
161
+ }
162
+
163
+ /**
164
+ * Check if date is same day
165
+ */
166
+
167
+ export function checkIfSameDay(d1: Date, d2: Date, checkTime: boolean = false) {
168
+ let date1, date2;
169
+ if (checkTime) {
170
+ date1 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate(), d1.getHours(), d1.getMinutes());
171
+ date2 = new Date(d2.getFullYear(), d2.getMonth(), d2.getDate(), d2.getHours(), d2.getMinutes());
172
+ } else {
173
+ date1 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate());
174
+ date2 = new Date(d2.getFullYear(), d2.getMonth(), d2.getDate());
175
+ }
176
+
177
+ return date1.getTime() === date2.getTime();
178
+ }
179
+
180
+ /**
181
+ * Get today at start of day
182
+ */
183
+
184
+ export function getTodayStartOfDay(timeZone?: string | null) {
185
+ const startDate = getFullDateTime(new Date(), {
186
+ locales: 'en-US',
187
+ alwaysShowYear: true,
188
+ hideTime: true,
189
+ });
190
+
191
+ const today = parseDateInTimezone(startDate, timeZone);
192
+ return today;
193
+ }
92
194
 
93
- const {
94
- locales = 'en-US',
95
- hideYear,
96
- hideDate,
97
- hideTime,
98
- showTextDate,
99
- alwaysShowYear
100
- } = params || {};
101
-
102
- let d;
103
- if (_d instanceof Date) {
104
- d = _d;
105
- } else {
106
- // Make sure _d is not null, before using this function
107
- d = _d ? new Date(_d) : new Date(-1);
108
- }
109
-
110
- if (hideDate) {
111
- return d.toLocaleTimeString(locales, {
112
- hour: 'numeric',
113
- minute: '2-digit'
114
- });
115
- }
116
-
117
- // If year is same year, then don't show year
118
- let hideYear_;
119
- if (!hideYear && !alwaysShowYear) {
120
- const dateYear = d.getFullYear();
121
- const currentYear = new Date().getFullYear();
122
- hideYear_ = dateYear === currentYear;
123
- } else if (hideYear || hideDate) {
124
- hideYear_ = true;
125
- }
126
-
127
- return d.toLocaleDateString(locales, {
128
- day: 'numeric',
129
- month: showTextDate ? 'short' : 'numeric',
130
- year: hideYear_ ? undefined : 'numeric',
131
- hour: hideTime ? undefined : 'numeric',
132
- minute: hideTime ? undefined : '2-digit'
133
- });
195
+ /**
196
+ * Get timezone enforced date
197
+ */
198
+
199
+ export function getCalDate(d: Date, timeZone_?: string | null) {
200
+ let timeZone = timeZone_ || undefined; // cannot be null, else it will throw error
201
+ if (timeZone && !isValidTimeZone(timeZone)) {
202
+ timeZone = undefined;
203
+ }
204
+
205
+ const usCalDate = d.toLocaleString('en-US', {
206
+ timeZone,
207
+ year: 'numeric',
208
+ month: '2-digit',
209
+ day: '2-digit',
210
+ });
211
+
212
+ // Get date in format YYYY-MM-DD
213
+ const [month, day, year] = usCalDate.split('/');
214
+ const calDate = `${year}-${month}-${day}`;
215
+ const calDateInt = Number(`${year}${month}${day}`);
216
+
217
+ const time = d.toLocaleString('en-US', {
218
+ timeZone,
219
+ hour: '2-digit',
220
+ minute: '2-digit',
221
+ second: '2-digit',
222
+ hour12: false,
223
+ });
224
+
225
+ return {
226
+ calDate,
227
+ calDateInt,
228
+ time,
229
+ };
134
230
  }
135
231
 
136
232
  /**
@@ -138,83 +234,82 @@ export function getFullTimeDate(
138
234
  */
139
235
 
140
236
  export function getTimeAgo(
141
- _d: Date | string | number | null,
142
- params?: Partial<TimeAgoParams>
237
+ _d: Date | string | number | null,
238
+ params?: Partial<TimeAgoParams>,
143
239
  ) {
144
-
145
- const {
146
- locales = 'en-US',
147
- justNowThresh = 300000, // 5 minutes
148
- nowThresh = 8.64e+7,
149
- disableFuture = false,
150
- isToday,
151
- skipTodayCheck,
152
- } = params || {};
153
-
154
- let d;
155
- if (_d instanceof Date) {
156
- d = _d
157
- } else if (!isNaN(Number(_d))) {
158
- d = new Date(Number(_d))
159
- } else {
160
- // Make sure date is not null, before using this function
161
- d = _d ? new Date(_d) : new Date(-1)
162
- }
163
-
164
- const ts = d.getTime();
165
- const now = Date.now();
166
- const diff = now - ts;
167
- const isFuture = diff < 0;
168
-
169
- if (isFuture && !disableFuture) {
170
- // Future date
171
-
172
- const minutesFromNow = Math.round(diff / 60000 * -1);
173
- if (minutesFromNow < 60) {
174
- return i18n.t('datetime.in_minutes_ct', { smart_count: minutesFromNow });
175
- }
176
-
177
- const fromIsToday = isToday || (!skipTodayCheck && getDatePeriod(d, new Date()) === 'TODAY');
178
- if (fromIsToday) {
179
- const hoursFromNow = Math.round(diff / 3600000 * -1);
180
- if (hoursFromNow <= 8) {
181
- return i18n.t('datetime.in_hours_ct', { smart_count: hoursFromNow });
182
- }
183
-
184
- return getFullTimeDate(d, {
185
- locales,
186
- hideDate: true,
187
- });
188
- }
189
- }
190
-
191
- if (!isFuture && diff < nowThresh) {
192
- if (diff < justNowThresh) {
193
- return i18n.t('datetime.just_now');
194
- }
195
-
196
- const minutesAgo = Math.round(diff / 60000);
197
- if (minutesAgo < 60) {
198
- return i18n.t('datetime.minutes_ago_ct', { smart_count: minutesAgo });
199
- }
200
-
201
- const agoIsToday = isToday || (!skipTodayCheck && getDatePeriod(d, new Date()) === 'TODAY');
202
- if (agoIsToday) {
203
- const hoursAgo = Math.round(diff / 3600000);
204
- if (hoursAgo <= 8) {
205
- return i18n.t('datetime.hours_ago_ct', { smart_count: hoursAgo });
206
- }
207
-
208
- return getFullTimeDate(d, {
209
- locales,
210
- hideDate: true,
211
- });
212
- }
213
- }
214
-
215
- return getFullTimeDate(d, {
216
- locales,
217
- });
240
+ const {
241
+ locales = 'en-US',
242
+ justNowThresh = 300000, // 5 minutes
243
+ nowThresh = 8.64e+7,
244
+ disableFuture = false,
245
+ isToday,
246
+ skipTodayCheck,
247
+ } = params || {};
248
+
249
+ let d;
250
+ if (_d instanceof Date) {
251
+ d = _d;
252
+ } else if (!isNaN(Number(_d))) {
253
+ d = new Date(Number(_d));
254
+ } else {
255
+ // Make sure date is not null, before using this function
256
+ d = _d ? new Date(_d) : new Date(-1);
257
+ }
258
+
259
+ const ts = d.getTime();
260
+ const now = Date.now();
261
+ const diff = now - ts;
262
+ const isFuture = diff < 0;
263
+
264
+ if (isFuture && !disableFuture) {
265
+ // Future date
266
+
267
+ const minutesFromNow = Math.round(diff / 60000 * -1);
268
+ if (minutesFromNow < 60) {
269
+ return i18n.t('datetime.in_minutes_ct', { smart_count: minutesFromNow });
270
+ }
271
+
272
+ const fromIsToday = isToday || (!skipTodayCheck && getDatePeriod(d, new Date()) === 'TODAY');
273
+ if (fromIsToday) {
274
+ const hoursFromNow = Math.round(diff / 3600000 * -1);
275
+ if (hoursFromNow <= 8) {
276
+ return i18n.t('datetime.in_hours_ct', { smart_count: hoursFromNow });
277
+ }
278
+
279
+ return getFullDateTime(d, {
280
+ locales,
281
+ hideDate: true,
282
+ });
283
+ }
284
+ }
285
+
286
+ if (!isFuture && diff < nowThresh) {
287
+ if (diff < justNowThresh) {
288
+ return i18n.t('datetime.just_now');
289
+ }
290
+
291
+ const minutesAgo = Math.round(diff / 60000);
292
+ if (minutesAgo < 60) {
293
+ return i18n.t('datetime.minutes_ago_ct', { smart_count: minutesAgo });
294
+ }
295
+
296
+ const agoIsToday = isToday || (!skipTodayCheck && getDatePeriod(d, new Date()) === 'TODAY');
297
+ if (agoIsToday) {
298
+ const hoursAgo = Math.round(diff / 3600000);
299
+ if (hoursAgo <= 8) {
300
+ return i18n.t('datetime.hours_ago_ct', { smart_count: hoursAgo });
301
+ }
302
+
303
+ return getFullDateTime(d, {
304
+ locales,
305
+ hideDate: true,
306
+ });
307
+ }
308
+ }
309
+
310
+ return getFullDateTime(d, {
311
+ locales,
312
+ });
218
313
  }
219
314
 
220
315
  /**
@@ -223,52 +318,58 @@ export function getTimeAgo(
223
318
  */
224
319
 
225
320
  export function getFullDate(
226
- _d: Date | string | number | null,
227
- locales: string = 'en-US',
228
- outputStyle: 'DATE_ONLY' | 'MINIMAL' | 'DETAILED' = 'DATE_ONLY',
321
+ _d: Date | string | number | null,
322
+ outputStyle: 'DATE_ONLY' | 'DATE_TEXT' | 'MINIMAL' | 'DETAILED' = 'DATE_ONLY',
323
+ locales: string = 'en-US',
229
324
  ) {
230
- let d;
231
- if (_d instanceof Date) {
232
- d = _d;
233
- } else {
234
- // Make sure _d is not null, before using this function
235
- d = _d ? new Date(_d) : new Date(-1);
236
- }
237
-
238
- switch (outputStyle) {
239
- case 'DATE_ONLY':
240
- // Expected output: "9/1/2024"
241
- return new Intl.DateTimeFormat(locales).format(d);
242
- case 'MINIMAL':
243
- // Expected output: "Sep 1, 2024, 6:54 PM"
244
- return new Intl.DateTimeFormat(locales, {
245
- dateStyle: 'medium', // 'full', 'long', 'medium', 'short'
246
- timeStyle: 'short', // 'full', 'long', 'medium', 'short'
247
- // timeZone: 'Australia/Sydney',
248
- }).format(d);
249
- case 'DETAILED':
250
- default:
251
- }
252
-
253
- // Expected output: "Sep 1, 2024 at 6:54 PM"
254
- const date = new Intl.DateTimeFormat(locales, {
255
- dateStyle: 'long', // 'full', 'long', 'medium', 'short'
256
- timeStyle: 'short', // 'full', 'long', 'medium', 'short'
257
- // timeZone: 'Australia/Sydney',
258
- }).format(d);
259
-
260
- const parts = new Intl.DateTimeFormat(locales, {
261
- dateStyle: 'long',
262
- timeStyle: 'long',
263
- }).formatToParts(d);
264
-
265
- const timezoneName = parts.find((part) => part.type === 'timeZoneName')?.value;
266
- if (timezoneName) {
267
- // Doing this will make sure {date} does not include [seconds] in the time format
268
- return date + ' ' + timezoneName;
269
- }
270
-
271
- return date;
325
+ let d;
326
+ if (_d instanceof Date) {
327
+ d = _d;
328
+ } else {
329
+ // Make sure _d is not null, before using this function
330
+ d = _d ? new Date(_d) : new Date(-1);
331
+ }
332
+
333
+ switch (outputStyle) {
334
+ case 'DATE_ONLY':
335
+ // Expected output: "9/1/2024"
336
+ return new Intl.DateTimeFormat(locales).format(d);
337
+ case 'MINIMAL':
338
+ // Expected output: "Sep 1, 2024, 6:54 PM"
339
+ return new Intl.DateTimeFormat(locales, {
340
+ dateStyle: 'medium', // 'full', 'long', 'medium', 'short'
341
+ timeStyle: 'short', // 'full', 'long', 'medium', 'short'
342
+ // timeZone: 'Australia/Sydney',
343
+ }).format(d);
344
+ case 'DATE_TEXT':
345
+ // Expected output: "September 1, 2024"
346
+ return new Intl.DateTimeFormat(locales, {
347
+ dateStyle: 'long',
348
+ // timeZone: 'Australia/Sydney',
349
+ }).format(d);
350
+ case 'DETAILED':
351
+ default:
352
+ }
353
+
354
+ // Expected output: "Sep 1, 2024 at 6:54 PM"
355
+ const date = new Intl.DateTimeFormat(locales, {
356
+ dateStyle: 'long', // 'full', 'long', 'medium', 'short'
357
+ timeStyle: 'short', // 'full', 'long', 'medium', 'short'
358
+ // timeZone: 'Australia/Sydney',
359
+ }).format(d);
360
+
361
+ const parts = new Intl.DateTimeFormat(locales, {
362
+ dateStyle: 'long',
363
+ timeStyle: 'long',
364
+ }).formatToParts(d);
365
+
366
+ const timezoneName = parts.find((part) => part.type === 'timeZoneName')?.value;
367
+ if (timezoneName) {
368
+ // Doing this will make sure {date} does not include [seconds] in the time format
369
+ return date + ' ' + timezoneName;
370
+ }
371
+
372
+ return date;
272
373
  }
273
374
 
274
375
  /**
@@ -276,83 +377,166 @@ export function getFullDate(
276
377
  */
277
378
 
278
379
  export function getDayPeriod(): 'MORNING' | 'AFTERNOON' | 'EVENING' | 'NIGHT' {
279
- const d = new Date();
280
- const h = d.getHours();
281
- if (h >= 5 && h < 12) {
282
- return 'MORNING';
283
- } else if (h >= 12 && h < 17) {
284
- return 'AFTERNOON';
285
- } else if (h >= 17 && h < 20) {
286
- return 'EVENING';
287
- }
288
- return 'NIGHT';
380
+ const d = new Date();
381
+ const h = d.getHours();
382
+ if (h >= 5 && h < 12) {
383
+ return 'MORNING';
384
+ } else if (h >= 12 && h < 17) {
385
+ return 'AFTERNOON';
386
+ } else if (h >= 17 && h < 20) {
387
+ return 'EVENING';
388
+ }
389
+ return 'NIGHT';
390
+ }
391
+
392
+ /**
393
+ * Convert YYYY-MM-DD to Date
394
+ */
395
+
396
+ export function getDateFromCalDate(calDate: string) {
397
+ const [year, month, day] = calDate.split('-');
398
+ return new Date(Number(year), Number(month) - 1, Number(day));
289
399
  }
290
400
 
291
401
  /**
292
402
  * Group by time period
403
+ *
404
+ * @param items - Array of items to group
405
+ * @param dateKey - Key in each item that contains the date
406
+ * @param mapFn - Optional function to map each item before grouping
407
+ *
408
+ * @returns Array of grouped items, each group contains items for a specific date period
409
+ */
410
+
411
+ export function groupByDatePeriod<T>(
412
+ items: T[],
413
+ dateKey: string,
414
+ groupByDate?: boolean,
415
+ timeZone?: string | null,
416
+ mapFn?: (item: any) => any
417
+ ): DatePeriodObj[][] {
418
+ const ordered = items.sort((a: any, b: any) => {
419
+ const valueA = a[dateKey];
420
+ const valueB = b[dateKey];
421
+
422
+ if (valueA < valueB) {
423
+ return 1;
424
+ }
425
+ if (valueA > valueB) {
426
+ return -1;
427
+ }
428
+ return 0;
429
+ });
430
+
431
+ const output = [];
432
+ const d = new Date();
433
+ // const timeZone = timeZone_; // || Intl.DateTimeFormat().resolvedOptions().timeZone;
434
+
435
+ let group: any[] | null = [];
436
+ for (const item of ordered) {
437
+ // Each group is grouped in date periods,
438
+ // e.g. "Tomorrow", "Today", "Yesterday", "Last Week", "Last Month", "Older"
439
+ // Group the ordered list by date period and push item to output
440
+
441
+ const lastItem = group[group.length - 1];
442
+ const lastDatePeriod: any = lastItem?.datePeriod;
443
+ const date = new Date((item as any)[dateKey]);
444
+ const datePeriod = groupByDate ? getCalDate(date, timeZone).calDate : getDatePeriod(date, d);
445
+
446
+ const dateObj = {
447
+ datePeriod,
448
+ date,
449
+ item: mapFn ? mapFn(item) : item,
450
+ };
451
+
452
+ if (lastDatePeriod && lastDatePeriod !== datePeriod && group.length) {
453
+ output.push(group);
454
+ group = [];
455
+ }
456
+
457
+ group.push(dateObj);
458
+ }
459
+
460
+ if (group.length) {
461
+ output.push(group);
462
+ }
463
+
464
+ return output;
465
+ }
466
+
467
+ /**
468
+ * Sort and label by date period
469
+ *
470
+ * @param items - Array of items to sort and label
471
+ * @param dateKey - Key in each item that contains the date
472
+ * @param mapFn - Optional function to map each item before grouping
473
+ *
474
+ * @returns Array of items sorted by date period, with labels for each period
475
+ */
476
+
477
+ export function labelSortByDatePeriod<T>(
478
+ items: T[],
479
+ dateKey: string,
480
+ groupByDate?: boolean,
481
+ timeZone?: string | null,
482
+ mapFn?: (item: any) => any
483
+ ): DatePeriodObj[] {
484
+ const ordered = items.sort((a: any, b: any) => {
485
+ const valueA = a[dateKey];
486
+ const valueB = b[dateKey];
487
+
488
+ if (valueA < valueB) {
489
+ return 1;
490
+ }
491
+ if (valueA > valueB) {
492
+ return -1;
493
+ }
494
+ return 0;
495
+ });
496
+
497
+ const output = [];
498
+ const d = new Date();
499
+
500
+ for (const item of ordered) {
501
+ const lastItem = output[output.length - 1];
502
+ const lastDatePeriod: any = lastItem?.datePeriod;
503
+ const date = new Date((item as any)[dateKey]);
504
+ const datePeriod = groupByDate ? getCalDate(date, timeZone).calDate : getDatePeriod(date, d);
505
+
506
+ const dateObj = {
507
+ datePeriod,
508
+ date,
509
+ item: mapFn ? mapFn(item) : item,
510
+ };
511
+
512
+ if (
513
+ (!output.length) ||
514
+ (lastDatePeriod && lastDatePeriod !== datePeriod)
515
+ ) {
516
+ output.push({
517
+ datePeriod,
518
+ date,
519
+ item: null,
520
+ });
521
+ }
522
+
523
+ output.push(dateObj);
524
+ }
525
+
526
+ return output;
527
+ }
528
+
529
+ /**
530
+ * Check if date is valid
293
531
  */
294
532
 
295
- export function groupByDatePeriod(items: any[], dateKey: string, isFlat: boolean = true, mapFn?: (item: any) => any) {
296
- const ordered = items.sort((a: any, b: any) => {
297
- const valueA = a[dateKey];
298
- const valueB = b[dateKey];
299
-
300
- if (valueA < valueB) {
301
- return 1;
302
- }
303
- if (valueA > valueB) {
304
- return -1;
305
- }
306
- return 0;
307
- });
308
-
309
- const output = [];
310
- const d = new Date();
311
-
312
- let group: any[] | null = [];
313
- for (const item of ordered) {
314
- // Each group is grouped in date periods,
315
- // e.g. "Tomorrow", "Today", "Yesterday", "Last Week", "Last Month", "Older"
316
- // Group the ordered list by date period and push item to output
317
- // If "isFlat" is true, output should be an array of arrays, else output should be a flat array
318
-
319
- const lastItem = isFlat ? output[output.length - 1] : group[group.length - 1];
320
- const lastDatePeriod: any = lastItem?.datePeriod;
321
- const datePeriod = getDatePeriod(new Date(item[dateKey]), d);
322
- const date = new Date(item[dateKey]);
323
-
324
- const dateObj = {
325
- datePeriod,
326
- date,
327
- item: mapFn ? mapFn(item) : item
328
- };
329
-
330
- if (
331
- (!output.length && isFlat) ||
332
- (lastDatePeriod && lastDatePeriod !== datePeriod)
333
- ) {
334
- if (isFlat) {
335
- output.push({
336
- datePeriod,
337
- date,
338
- item: null
339
- });
340
- } else if (group.length) {
341
- output.push(group);
342
- group = [];
343
- }
344
- }
345
-
346
- if (!isFlat) {
347
- group.push(dateObj);
348
- } else {
349
- output.push(dateObj);
350
- }
351
- }
352
-
353
- if (group.length) {
354
- output.push(group);
355
- }
356
-
357
- return output;
533
+ export function isValidDate(d?: Date | string | number | null) {
534
+ if (d instanceof Date) {
535
+ return !isNaN(d.getTime());
536
+ }
537
+ if (typeof d === 'string' || typeof d === 'number') {
538
+ const date = new Date(d);
539
+ return !isNaN(date.getTime());
540
+ }
541
+ return false;
358
542
  }