parse-human-interval
v1.0.0
Published
Parse human-readable time intervals into milliseconds timestamp ranges
Readme
Parse Human Interval
A TypeScript function that parses human-readable time interval strings into timestamp ranges.
Usage
import { parseHumanInterval } from "./parser.js";
// Returns { start: number, end: number } with timestamps in milliseconds
const result = parseHumanInterval("2 weeks ago");
console.log(result); // { start: 1234567890000, end: 1234567890000 }Supported Patterns
All intervals end at current time unless specified otherwise:
"today"→ midnight to now"yesterday"→ yesterday midnight to yesterday 11:59:59 PM"2 weeks ago"or"two weeks ago"→ exactly 2 weeks before now to now"1 week"or"one week"→ from 1 week ago to now"3 days"→ from 3 days ago to now
Number Formats
- Digits: 1-99 (e.g., "7 days", "15 weeks")
- Words: one through twenty (e.g., "three months", "fifteen days")
Supported Units
day/daysweek/weeksmonth/months(approximated as 30 days)
Input Normalization
The function automatically handles:
- Extra whitespace
- Mixed case
- Optional "ago" suffix
- Singular/plural units
Examples
parseHumanInterval("today"); // Today from midnight to now
parseHumanInterval("yesterday"); // Yesterday full day
parseHumanInterval("7 days"); // Last 7 days
parseHumanInterval("two weeks ago"); // Last 2 weeks
parseHumanInterval("1 month"); // Last 30 days
parseHumanInterval(" 3 DAYS AGO "); // Last 3 days (normalized)Invalid Inputs
Returns null for:
- Empty strings
- Non-string inputs
- Unsupported patterns
- Numbers outside 0-99 range
- Unsupported time units
- Fractional numbers
- Compound expressions
Testing
npm testRuns comprehensive table-driven tests covering all patterns, edge cases, and invalid inputs using Node.js built-in test runner.
