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
export async function convertRelativeDateToString({
relativeDate = "0 days ago", // Default search if no query is provided
}: {
relativeDate?: string;
}): Promise<Response> {
const now = new Date();
const amount = parseInt(relativeDate);
const unit = relativeDate.match(/[a-zA-Z]+/)[0];
let milliseconds;
switch (unit.toLowerCase()) {
case "h":
case "hr":
case "hrs":
case "hour":
case "hours":
milliseconds = amount * 60 * 60 * 1000;
break;
case "d":
case "day":
case "days":
milliseconds = amount * 24 * 60 * 60 * 1000;
break;
case "w":
case "wk":
case "week":
case "weeks":
milliseconds = amount * 7 * 24 * 60 * 60 * 1000;
break;
case "m":
case "mo":
case "month":
case "months":
milliseconds = amount * 30 * 24 * 60 * 60 * 1000;
break;
case "y":
case "yr":
case "year":
case "years":
milliseconds = amount * 365 * 24 * 60 * 60 * 1000;
break;
default:
throw new Error("Invalid time unit");
}
const pastDate = new Date(now.getTime() - milliseconds);
const options = { year: "numeric", month: "short", day: "numeric" };
const dateString = pastDate.toLocaleDateString("en-US", options);
return new Response(dateString, {
headers: { "Content-Type": "text/plain" },
status: 200,
});
}