-
Notifications
You must be signed in to change notification settings - Fork 0
Collapse file tree
Files
Search this repository
/
Copy pathdate.tsx
More file actions
More file actions
64 lines (53 loc) · 1.37 KB
/
date.tsx
File metadata and controls
64 lines (53 loc) · 1.37 KB
You must be signed in to make or propose changes
More edit options
Edit and raw actions
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
export function handleDate(input: string = getToday()) {
if (!isValid(input)) {
return null;
}
const isoDatetime = `${input}T00:00:00Z`;
const date = new Date(isoDatetime);
// "Thursday, January 1, 1970"
const dateWithWeekday = date.toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
});
return {
title: dateWithWeekday,
heading: <time datetime={isoDatetime}>{dateWithWeekday}</time>,
data: {
'ISO 8601': input,
'Unix time': Math.floor(date.getTime() / 1000),
},
};
}
function isValid(input: string) {
const match = input.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
if (!match) {
return false;
}
const [year, month, day] = match.slice(1).map((str) => parseInt(str, 10));
if (
!((1583 <= year && year <= 9999)
&& (1 <= month && month <= 12)
&& (1 <= day && day <= 31))
) {
return false;
}
const date = new Date(`${input}T00:00:00Z`);
return (
date.getUTCFullYear() === year
&& date.getUTCMonth() === month - 1
&& date.getUTCDate() === day
);
}
/**
* Returns the current date in UTC as an ISO string (YYYY-MM-DD)
*/
function getToday(): string {
const now = new Date();
return [
now.getUTCFullYear(),
String(now.getUTCMonth() + 1).padStart(2, '0'),
String(now.getUTCDate()).padStart(2, '0'),
].join('-');
}