Human-Readable Date Range Parser

raw JSON →
1.1.0 verified Thu Apr 23 auth: no javascript

`dates-range-parser` is a JavaScript library designed to parse and interpret human-readable date and time expressions, converting them into structured date ranges. It is currently at version 1.1.0 and appears to have an active development status, with its latest minor release introducing target timezone calculations. The library differentiates itself by supporting a wide array of formats, including relative expressions like 'yesterday', 'next week', and 'now -> 7days', as well as specific date/time strings and duration-based ranges such as '3days'. A key feature is its flexible timezone handling through `UTC` and `TZ` properties, allowing calculations in local time, UTC, or a specified target timezone. It also permits overriding the definition of 'now' for consistent testing or specific scenario handling. The output format consistently provides `start` and `end` properties, representing seconds since epoch, or `null` for unconstrained ranges. This output is often directly consumable by databases or search services.

error TypeError: DatesRangeParser.parse is not a function
cause The `DatesRangeParser` object was imported incorrectly, likely as a named import instead of a default import, or attempting to instantiate it as a class.
fix
For ESM, use import DatesRangeParser from 'dates-range-parser';. For CommonJS, use const DatesRangeParser = require('dates-range-parser');. Ensure you are calling parse as a static method on the imported object.
error JavaScript Date object shows wrong time or day after parsing.
cause This is typically due to a mismatch between the library's timezone settings (`.UTC` or `.TZ`) and the desired interpretation, or because the output values (seconds since epoch) are mistakenly treated as milliseconds by `new Date()` and then interpreted in the local timezone.
fix
Verify the DatesRangeParser.UTC and DatesRangeParser.TZ settings. Remember that start and end are seconds since epoch; multiply by 1000 for JavaScript Date objects: new Date(range.start * 1000). If TZ is set, the from/to values in value object are milliseconds but represent the start/end of the day *in the target timezone*, which might convert to a different UTC day.
error Parsing '2023-01-01 ->' or '-> 2023-01-01' results in `null` or an unexpected single-date range.
cause The library's interpretation of open-ended ranges might differ from expectations. While `2011-05 ->` is documented, complex open-ended syntax might not always be supported as intuitively as simpler ranges.
fix
Consult the 'Quick Syntax Guide' and 'Syntax in More Detail' in the README for exact supported open-ended formats. For 'open to the future', end will be null. For 'open to the past', start will be null. Ensure your input string precisely matches documented patterns.
gotcha The `start` and `end` properties returned by `DatesRangeParser.parse()` represent seconds since epoch, not milliseconds. Directly passing these values to `new Date(timestamp)` in JavaScript will result in an `Invalid Date` or an incorrect date because `Date` constructor expects milliseconds.
fix Multiply the `start` and `end` values by 1000 before creating a JavaScript `Date` object: `new Date(range.start * 1000)`.
gotcha The `DatesRangeParser.UTC` property (default `false`) globally affects how all date calculations are performed, converting input and output to UTC if set to `true`. Be aware that changing this property affects all subsequent `parse` calls.
fix Set `DatesRangeParser.UTC = true;` at the beginning of your application or before a block of UTC-dependent parsing. Remember to reset it or manage its state carefully if your application requires mixed local and UTC calculations.
gotcha Since version 1.1.0, the `DatesRangeParser.TZ` property allows specifying a target IANA timezone for relative calculations. If set, this overrides `UTC` settings for relative date expressions, leading to potentially different 'today', 'tomorrow', 'next week' etc., depending on the specified timezone.
fix Set `DatesRangeParser.TZ = 'Your/Timezone';` (e.g., 'Asia/Karachi') to perform relative calculations in that timezone. Ensure this is managed in contexts where multiple timezones might be relevant.
gotcha The `DatesRangeParser.now` property can be overridden globally to define a specific 'current time' for all relative date calculations. If not reset, this can lead to unexpected or stale results, especially in long-running processes or server environments.
fix Override `DatesRangeParser.now` only when necessary (e.g., for testing or specific batch processing) and consider resetting it to `undefined` or `new Date()` afterwards to revert to the system's current time.
gotcha The `DatesRangeParser.parse()` method returns `null` if the input string cannot be successfully parsed into a date range, rather than throwing an error. Developers must explicitly check for `null` results.
fix Always check the return value of `DatesRangeParser.parse()` for `null` before attempting to access its `start` or `end` properties: `const result = DatesRangeParser.parse(input); if (result) { /* use result */ } else { /* handle invalid input */ }`.
npm install dates-range-parser
yarn add dates-range-parser
pnpm add dates-range-parser

This quickstart demonstrates how to import and use the `DatesRangeParser` to interpret various date expressions, including relative and duration-based ranges, considering UTC and specific time zones. It also highlights how to interpret the output for JavaScript Date objects.

import DatesRangeParser from 'dates-range-parser';

// Set to UTC mode for database-friendly outputs (optional, default is local time)
DatesRangeParser.UTC = true;

// Override 'now' for consistent testing or specific scenarios (optional)
DatesRangeParser.now = new Date(Date.UTC(2023, 0, 15, 12, 0, 0)); // Jan 15, 2023 12:00:00 UTC

// Example 1: Parse a relative date
const yesterdayRange = DatesRangeParser.parse('yesterday');
console.log('Yesterday (UTC):', {
  start: yesterdayRange ? new Date(yesterdayRange.start * 1000) : null,
  end: yesterdayRange ? new Date(yesterdayRange.end * 1000) : null
});

// Example 2: Parse a duration from 'now'
const sevenDaysFromNow = DatesRangeParser.parse('now -> 7days');
console.log('Next 7 days from overridden now (UTC):', {
  start: sevenDaysFromNow ? new Date(sevenDaysFromNow.start * 1000) : null,
  end: sevenDaysFromNow ? new Date(sevenDaysFromNow.end * 1000) : null
});

// Example 3: Use specific timezone (since v1.1.0)
DatesRangeParser.UTC = false; // Reset to local calculations
DatesRangeParser.TZ = 'Asia/Karachi'; // Pakistan Standard Time, UTC+5
DatesRangeParser.now = new Date(1631212800000); // 09 September 2021 20:00:00 UTC
const karachiToday = DatesRangeParser.parse('today');
console.log('Today in Asia/Karachi (from UTC now):', {
  from: karachiToday?.value?.from ? new Date(karachiToday.value.from) : null,
  to: karachiToday?.value?.to ? new Date(karachiToday.value.to) : null
});

// Reset to default behavior for subsequent operations if needed
DatesRangeParser.UTC = false;
DatesRangeParser.TZ = null;
DatesRangeParser.now = undefined;