MCPcopy
hub / github.com/cloudflare/mcp-server-cloudflare / parseRelativeTime

Function parseRelativeTime

packages/mcp-common/src/utils.ts:8–33  ·  view source on GitHub ↗
(input: string)

Source from the content-addressed store, hash-verified

6 * Parse a relative time string into seconds
7 */
8export function parseRelativeTime(input: string): number {
9 const units = { s: 1, m: 60, h: 3600, d: 86400, w: 604800 } as const
10
11 const cleanedInput = input.replace(/\s+/g, '').toLowerCase()
12 if (!/^[+-](?:\d+[smhdw]){1,}$/.test(cleanedInput)) {
13 throw new Error(`Invalid relative time format: ${input}`)
14 }
15
16 const sign = cleanedInput.startsWith('-') ? -1 : 1
17
18 const timeStr = cleanedInput.slice(1) // Remove the sign
19 const matches = timeStr.match(/\d+[smhdw]/g)
20
21 if (!matches) {
22 throw new Error(`No matches found while parsing relative time: ${timeStr}`)
23 }
24
25 const seconds = matches.reduce((total, match) => {
26 const value = parseInt(match)
27 const unit = match.slice(-1) as keyof typeof units
28
29 return total + value * units[unit]
30 }, 0)
31
32 return sign * seconds
33}
34
35/**
36 * Get the current time as an ISO string without milliseconds

Callers 2

utils.spec.tsFile · 0.90

Calls 1

replaceMethod · 0.65

Tested by

no test coverage detected