@jsb188/app 1.0.4 → 1.1.3

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