Skip to content

Commit 29a7194

Browse files
committed
Added helper for parsing and validating dates in yyyy-mm-dd format
1 parent ba04864 commit 29a7194

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { ValidationError } from '../errors';
2+
3+
export const formatDateToUtcYYYYMMDD = (date: Date) => {
4+
// Use the 'en-CA' locale which formats as 'yyyy-mm-dd'
5+
const formatter = new Intl.DateTimeFormat('en-CA', {
6+
timeZone: 'UTC',
7+
year: 'numeric',
8+
month: '2-digit',
9+
day: '2-digit',
10+
});
11+
12+
// Format the date
13+
return formatter.format(date);
14+
};
15+
16+
// Function to validate 'yyyy-mm-dd' format
17+
export const isValidYYYYMMDD = (dateString: string) => {
18+
const regex = /^\d{4}-\d{2}-\d{2}$/;
19+
return regex.test(dateString);
20+
};
21+
22+
export const parseDateFromUtcYYYYMMDD = (dateString: string) => {
23+
const date = new Date(dateString + 'T00:00:00Z');
24+
25+
if (!isValidYYYYMMDD(dateString)) {
26+
throw new ValidationError('Invalid date format, must be yyyy-mm-dd');
27+
}
28+
29+
if (isNaN(date.getTime())) {
30+
throw new ValidationError('Invalid date format');
31+
}
32+
33+
return date;
34+
};

src/packages/emmett/src/validation/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,5 @@ export const assertUnsignedBigInt = (value: string): bigint => {
3333
}
3434
return number;
3535
};
36+
37+
export * from './dates';

0 commit comments

Comments
 (0)