28 lines
860 B
TypeScript
28 lines
860 B
TypeScript
export function createDateFromRelativeTime(text: string) {
|
|
const now = new Date();
|
|
const cleanText = text
|
|
.toLowerCase()
|
|
.replace("posted", "")
|
|
.replace("ago", "")
|
|
.trim();
|
|
|
|
// Parse common patterns
|
|
const patterns = [
|
|
{ regex: /(\d+)\s*d/, multiplier: 24 * 60 * 60 * 1000 },
|
|
{ regex: /(\d+)\s*h/, multiplier: 60 * 60 * 1000 },
|
|
{ regex: /(\d+)\s*hr/, multiplier: 60 * 60 * 1000 },
|
|
{ regex: /(\d+)\s*min/, multiplier: 60 * 1000 },
|
|
{ regex: /(\d+)\s*m(?!in)/, multiplier: 60 * 1000 },
|
|
{ regex: /(\d+)\s*s/, multiplier: 1000 },
|
|
];
|
|
|
|
for (const pattern of patterns) {
|
|
const match = cleanText.match(pattern.regex);
|
|
if (match) {
|
|
const value = parseInt(match[1]);
|
|
return new Date(now.getTime() - value * pattern.multiplier);
|
|
}
|
|
}
|
|
|
|
throw new Error(`Could not parse time string: ${text}`);
|
|
}
|