### Run Chrono Examples in Node.js
Source: https://github.com/wanasit/chrono/blob/master/examples/nodejs_minimal/README.md
Install dependencies and run the CommonJS and ECMAScript module examples. Both should produce similar output indicating successful date parsing.
```bash
npm install
node import_in_commonjs.js
# Should print "An appointment on Sep 12-13 2022-09-12..."
node import_in_ecma.mjs
# Should print "An appointment on Sep 12-13 2022-09-12..."
```
--------------------------------
### Example Timezone Configuration (CET)
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/calculation-utilities.md
An example configuration for the Central European Time (CET) timezone, demonstrating how to define DST offsets and functions to determine DST start and end dates within a given year.
```typescript
CET: {
timezoneOffsetDuringDst: 2 * 60, // UTC+2
timezoneOffsetNonDst: 60, // UTC+1
dstStart: (year) => getLastWeekdayOfMonth(year, Month.MARCH, Weekday.SUNDAY, 2),
dstEnd: (year) => getLastWeekdayOfMonth(year, Month.OCTOBER, Weekday.SUNDAY, 3),
}
```
--------------------------------
### Clone and Install Chrono Library
Source: https://github.com/wanasit/chrono/blob/master/README.md
Clone the Chrono repository from GitHub and install its dependencies using npm.
```bash
# Clone and install library
$ git clone https://github.com/wanasit/chrono.git chrono
$ cd chrono
$ npm install
```
--------------------------------
### Custom Refiner Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/chrono.md
Example of a custom refiner that adjusts times between 1 AM and 4 AM to be PM if no meridiem is specified. It iterates through results and modifies the start time components.
```typescript
const meridiemRefiner: Refiner = {
refine: (context, results) => {
results.forEach((result) => {
if (!result.start.isCertain('meridiem') &&
result.start.get('hour') >= 1 &&
result.start.get('hour') < 4) {
result.start.assign('meridiem', 1);
result.start.assign('hour', result.start.get('hour') + 12);
}
});
return results;
}
};
```
--------------------------------
### Install Chrono Node Package
Source: https://github.com/wanasit/chrono/blob/master/README.md
Install the chrono-node package using npm for use in your project.
```bash
$ npm install --save chrono-node
```
--------------------------------
### English Locale Configuration Implementation
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/locales.md
Example implementation of a locale configuration for English, providing methods for casual and strict configurations.
```typescript
// src/locales/en/configuration.ts
export default class ENDefaultConfiguration {
createCasualConfiguration(littleEndian = false): Configuration { ... }
createConfiguration(strictMode = true, littleEndian = false): Configuration { ... }
}
```
--------------------------------
### Example: Custom Timezones
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/configuration.md
Illustrates how to override existing timezone abbreviations or define new custom timezones, including DST-aware configurations.
```typescript
import chrono from 'chrono-node';
// Override a standard timezone
const results1 = chrono.parse('10:00 EST', undefined, {
timezones: { EST: -300 } // UTC-5 (minutes)
});
console.log(results1[0].start.get('timezoneOffset')); // -300
// Add a custom timezone
const results2 = chrono.parse('10:00 XYZ', undefined, {
timezones: { XYZ: -180 } // UTC-3
});
// DST-aware timezone
import { Weekday, Month } from 'chrono-node';
import { getLastWeekdayOfMonth } from 'chrono-node';
const customTz = {
timezoneOffsetDuringDst: -240, // UTC-4 (EDT)
timezoneOffsetNonDst: -300, // UTC-5 (EST)
dstStart: (year) => getLastWeekdayOfMonth(year, Month.MARCH, Weekday.SUNDAY, 2),
dstEnd: (year) => getLastWeekdayOfMonth(year, Month.NOVEMBER, Weekday.SUNDAY, 1)
};
const results3 = chrono.parse('10:00 ET', undefined, {
timezones: { ET: customTz }
});
```
--------------------------------
### Duration Usage Examples
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/calculation-utilities.md
Illustrates how to create Duration objects for future and past time intervals, including examples with negative values and fractional days. Fractional values are automatically cascaded.
```typescript
import { addDuration } from 'chrono-node';
// 5 days and 3 hours in the future
const duration: Duration = { day: 5, hour: 3 };
// 2 weeks in the past
const pastDuration: Duration = { week: -2 };
// Fractional: 1.5 days
const fractional: Duration = { day: 1.5 }; // 1 day + 12 hours
```
--------------------------------
### TypeScript Usage Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
Demonstrates how to use Chrono-Node with TypeScript, including type-safe parsing of dates and results. Ensure your TypeScript configuration is compatible.
```typescript
import chrono from 'chrono-node';
// Full type support
const results: ParsedResult[] = chrono.parse('tomorrow');
const date: Date | null = chrono.parseDate('3pm');
```
--------------------------------
### ParsedResult Example Usage
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/types.md
Demonstrates how to access properties and methods of a ParsedResult object after parsing input text. Shows how to get the index, matched text, start components, and the resulting Date object.
```typescript
const results = chrono.parse("Tomorrow at 3pm");
if (results.length > 0) {
const result = results[0];
console.log(result.index); // 0
console.log(result.text); // "Tomorrow at 3pm"
console.log(result.start.get("day")); // Tomorrow's day
console.log(result.date()); // JavaScript Date object
}
```
--------------------------------
### Main Entry Points for Chrono
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/README.md
Provides examples of how to use the main entry points for parsing text into dates using the Chrono library. Includes quick parsing, pre-configured instances for casual and strict parsing, and locale-specific parsing.
```typescript
import chrono, { en } from 'chrono-node';
// Quick parse
chrono.parse(text, ref, option); // → ParsedResult[]
chrono.parseDate(text, ref, option); // → Date | null
// Pre-configured instances
chrono.casual.parse(text, ref, option); // English casual
chrono.strict.parse(text, ref, option); // English strict
// Locales
en.casual.parse(...);
en.strict.parse(...);
en.GB.parse(...); // UK format (DD/MM)
fr.parseDate(...); // French
ja.parseDate(...); // Japanese
```
--------------------------------
### Using Chrono in a Browser with ES Module
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
This example demonstrates how to import and use the Chrono library in a web browser using an ES module from a CDN. It parses the string 'tomorrow' into a date object.
```html
```
--------------------------------
### Duration Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/types.md
Illustrates how to create a Duration object to represent a specific time interval in the future.
```typescript
const duration: Duration = {
day: 5,
hour: 2,
minute: 30
};
// Represents 5 days, 2 hours, and 30 minutes into the future
```
--------------------------------
### Custom Parser Example
Source: https://github.com/wanasit/chrono/blob/master/README.md
Adds a custom parser to recognize 'Christmas' and extract the date components for December 25th.
```javascript
const custom = chrono.casual.clone();
custom.parsers.push({
pattern: () => { return /\bChristmas\b/i },
extract: (context, match) => {
return {
day: 25, month: 12
}
}
});
custom.parseDate("I'll arrive at 2.30AM on Christmas night");
// Wed Dec 25 2013 02:30:00 GMT+0900 (JST)
// 'at 2.30AM on Christmas'
```
--------------------------------
### Custom Parser Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/chrono.md
Example of a custom parser for the DD.MM.YYYY date format. It defines a RegExp pattern and an extraction function to parse the matched components.
```typescript
const customParser: Parser = {
pattern: (context) => /(\d{1,2})\.(\d{1,2})\.(\d{4})/,
extract: (context, match) => {
return {
day: parseInt(match[1]),
month: parseInt(match[2]),
year: parseInt(match[3])
};
}
};
const chrono = new Chrono({
parsers: [customParser],
refiners: []
});
const date = chrono.parseDate('15.12.2024');
// Fri Dec 15 2024 12:00:00 GMT+0000
```
--------------------------------
### CommonJS Module Import
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
Example of importing and using Chrono-Node within a CommonJS environment. This is typically used in older Node.js projects or specific build setups.
```javascript
const chrono = require('chrono-node');
const date = chrono.parseDate('tomorrow');
```
--------------------------------
### date()
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
Returns the start date as a JavaScript Date object. This method is equivalent to calling `this.start.date()` and is useful for obtaining the parsed date directly.
```APIDOC
## date()
### Description
Returns the start date as a JavaScript Date object.
### Method
```typescript
date(): Date
```
### Example
```typescript
const results = chrono.parse("tomorrow");
const date = results[0].date(); // Tomorrow's date at noon
```
```
--------------------------------
### CustomRangeRefiner Implementation Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parser-refiner-abstractions.md
An example implementation of `AbstractMergeDateRangeRefiner`. This refiner merges results separated by ' to ' or '-'.
```typescript
class CustomRangeRefiner extends AbstractMergeDateRangeRefiner {
shouldMergeResults(
textBetween: string,
prevResult: ParsingResult,
nextResult: ParsingResult
): boolean {
// Merge if separated by " to " or "-"
return /^\s*(?:to|-)\s*$/.test(textBetween);
}
}
```
--------------------------------
### Clone and Extend Existing Chrono Configuration
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/configuration.md
Start with a predefined configuration (like English casual) and modify its parsers and refiners. Allows for incremental customization.
```typescript
import { en } from 'chrono-node';
// Start with English casual configuration
const customChrono = en.casual.clone();
// Add or remove parsers
customChrono.parsers.push(myCustomParser);
customChrono.refiners.unshift(myCustomRefiner);
// Use the customized instance
const results = customChrono.parse('my custom format');
```
--------------------------------
### DST-Aware Timezone Configuration Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/configuration.md
Configure a timezone with specific DST rules, including offset changes and start/end dates for DST. Used when creating a custom Chrono instance.
```typescript
import { Weekday, Month } from 'chrono-node';
// Eastern Time with automatic DST handling
const ETConfig = {
timezoneOffsetDuringDst: -240, // EDT: UTC-4
timezoneOffsetNonDst: -300, // EST: UTC-5
dstStart: (year) => {
// Second Sunday of March at 2:00 AM
return new Date(year, Month.MARCH - 1, 1); // Simplified
},
dstEnd: (year) => {
// First Sunday of November at 2:00 AM
return new Date(year, Month.NOVEMBER - 1, 1); // Simplified
}
};
chrono.parse('3pm ET', undefined, {
timezones: { ET: ETConfig }
});
```
--------------------------------
### Custom Refiner Example for Meridiem
Source: https://github.com/wanasit/chrono/blob/master/README.md
Adds a custom refiner to automatically assign PM to times between 1:00 and 4:00 if no AM/PM is specified.
```javascript
const custom = chrono.casual.clone();
custom.refiners.push({
refine: (context, results) => {
// If there is no AM/PM (meridiem) specified,
// let all time between 1:00 - 4:00 be PM (13.00 - 16.00)
results.forEach((result) => {
if (!result.start.isCertain('meridiem') &&
result.start.get('hour') >= 1 && result.start.get('hour') < 4) {
result.start.assign('meridiem', 1);
result.start.assign('hour', result.start.get('hour') + 12);
}
});
return results;
}
});
// This will be parsed as PM.
// > Tue Dec 16 2014 14:30:00 GMT-0600 (CST)
custom.parseDate("This is at 2.30");
// Unless the 'AM' part is specified
// > Tue Dec 16 2014 02:30:00 GMT-0600 (CST)
custom.parseDate("This is at 2.30 AM");
```
--------------------------------
### CustomDateTimeRefiner Implementation Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parser-refiner-abstractions.md
An example implementation of `AbstractMergeDateTimeRefiner`. This refiner merges date and time if they are close and separated by ' at '.
```typescript
class CustomDateTimeRefiner extends AbstractMergeDateTimeRefiner {
shouldMergeResults(
textBetween: string,
prevResult: ParsingResult,
nextResult: ParsingResult
): boolean {
// Merge date + time if close together with " at "
return /^\s+at\s+$/.test(textBetween);
}
}
```
--------------------------------
### English Locale - UK (GB)
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/locales.md
Example of using the UK English variant for parsing dates, respecting the day-first format.
```APIDOC
## English (en) - UK Variant (GB)
```typescript
import { en } from 'chrono-node';
// UK-style date format (day-first)
en.GB.parse('6/10/2018'); // October 6, 2018 (day-first format)
en.GB.parseDate('Friday'); // Next Friday
```
```
--------------------------------
### Example: forwardDate Option
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/configuration.md
Demonstrates how the `forwardDate` option influences relative date parsing. When true, results are biased towards dates after the reference date.
```typescript
import chrono from 'chrono-node';
const refDate = new Date(2024, 5, 15); // Jun 15, 2024 (Saturday)
// Default: closest Friday is yesterday (Jun 14)
const results1 = chrono.parse('Friday', refDate);
console.log(results1[0].start.get('day')); // 14
// With forwardDate: next Friday is Jun 21
const results2 = chrono.parse('Friday', refDate, { forwardDate: true });
console.log(results2[0].start.get('day')); // 21
```
--------------------------------
### English Locale - US (Casual)
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/locales.md
Example of using the default US English locale in casual mode for parsing dates and times with informal expressions.
```APIDOC
## English (en) - US Variant (Casual)
```typescript
import chrono from 'chrono-node';
// Default is US English casual
chrono.parse('6/10/2018'); // June 10, 2018 (month-first format)
chrono.parseDate('tomorrow at 3pm'); // Tomorrow at 3 PM
```
```
--------------------------------
### get()
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
Retrieves the value of a date/time component, whether it was explicitly stated or inferred from the context. Returns null if the component is completely unknown.
```APIDOC
## get()
### Description
Returns the value of a component, whether **certain** or **implied**. Returns null if the component is unknown.
### Method
```typescript
get(component: Component): number | null
```
### Parameters
#### Path Parameters
- **component** (Component) - Required - The component to retrieve
### Returns
`number | null` - The component value or null if completely unknown
### Important
Always returns calendar values:
- Months: 1-12 (1 = January)
- Days: 1-31
- Hours: 0-23
- Weekday: 0-6 (0 = Sunday)
- Meridiem: 0 (AM) or 1 (PM)
### Example
```typescript
import chrono from 'chrono-node';
const results = chrono.parse('tomorrow at 3pm');
const components = results[0].start;
console.log(components.get('day')); // Tomorrow's day number
console.log(components.get('month')); // Tomorrow's month (1-12)
console.log(components.get('year')); // Current year
console.log(components.get('hour')); // 15 (3pm in 24-hour)
console.log(components.get('minute')); // 0 (implied)
console.log(components.get('meridiem')); // 1 (PM)
// For unknown components
const unknownValue = components.get('millisecond');
// Returns 0 (implied default) - not null in this case
// Try a component that might not be set
const weekday = components.get('weekday');
// Returns the implied weekday if day was set, or null if completely unknown
```
```
--------------------------------
### Importing Locales with Intl Issues
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/errors.md
Demonstrates how to import locales for chrono-node. The first example may fail if the Intl module is disabled, while the second works better in such scenarios.
```typescript
// May fail if Intl module disabled
import chrono from 'chrono-node';
```
```typescript
// Works better with Intl disabled
import chrono from 'chrono-node/en';
```
--------------------------------
### Parsing with Reference Instant and Timezone
Source: https://github.com/wanasit/chrono/blob/master/README.md
Provide an `instant` (Date object) and `timezone` string for precise parsing of time-sensitive phrases. This example shows parsing 'Friday at 4pm' with a specific instant and timezone.
```javascript
chrono.parseDate("Friday at 4pm", {
// Wed Jun 09 2021 21:00:00 GMT+0900 (JST)
// = Wed Jun 09 2021 07:00:00 GMT-0500 (CDT)
instant: new Date(1623240000000),
timezone: "CDT",
})
// Sat Jun 12 2021 06:00:00 GMT+0900 (JST)
// = Fri Jun 11 2021 16:00:00 GMT-0500 (CDT)
```
--------------------------------
### tags()
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
Returns a Set of combined debugging tags from both start and end components. This is useful for debugging parsing results.
```APIDOC
## tags()
### Description
Returns combined debugging tags from both start and end components.
### Method
```typescript
tags(): Set
```
### Returns
`Set` - Union of all tags
```
--------------------------------
### ECMAScript Modules (ESM) Import
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
Example of importing and using Chrono-Node with ECMAScript Modules (ESM). This is the modern standard for JavaScript modules in Node.js.
```javascript
import chrono from 'chrono-node';
const date = chrono.parseDate('tomorrow');
```
--------------------------------
### Custom Month Parser Implementation
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parser-refiner-abstractions.md
Example of a custom parser extending `AbstractParserWithWordBoundaryChecking` to parse month names. Requires `innerPattern` and `innerExtract` implementation.
```typescript
import { AbstractParserWithWordBoundaryChecking } from 'chrono-node';
import { ParsingContext } from 'chrono-node';
import { Component } from 'chrono-node';
class CustomMonthParser extends AbstractParserWithWordBoundaryChecking {
innerPattern(context: ParsingContext): RegExp {
return /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*/i;
}
innerExtract(context: ParsingContext, match: RegExpMatchArray) {
const months: { [key: string]: number } = {
'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12
};
const month = months[match[0].toLowerCase()];
if (!month) return null;
return { month };
}
}
// Usage
const parser = new CustomMonthParser();
const chrono = new Chrono({
parsers: [parser],
refiners: []
});
```
--------------------------------
### Custom Timezone Parsing (Simple Offset)
Source: https://github.com/wanasit/chrono/blob/master/README.md
Configure custom timezone abbreviations to offsets using the `timezones` option. This example maps 'XYZ' to a fixed GMT-0300 offset.
```javascript
// Chrono doesn't understand XYZ, so no timezone is parsed
chrono.parse('at 10:00 XYZ', new Date(2023, 3, 20))
// "knownValues": {"hour": 10, "minute": 0}
// Make Chrono parse XYZ as offset GMT-0300 (180 minutes)
chrono.parse('at 10:00 XYZ', new Date(2023, 3, 20), { timezones: { XYZ: -180 } })
// "knownValues": {"hour": 10, "minute": 0, "timezoneOffset": -180}
```
--------------------------------
### Get Start Date as Date Object
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
Retrieves the start date of a parsed result as a JavaScript Date object. This is equivalent to calling `this.start.date()`.
```typescript
date(): Date
```
```typescript
const results = chrono.parse("tomorrow");
const date = results[0].date(); // Tomorrow's date at noon
```
--------------------------------
### Importing and Using Predefined Chrono Instances
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/chrono.md
Demonstrates how to import and use various predefined Chrono instances for different locales and parsing strictness levels. These instances offer convenient access to pre-configured parsing pipelines.
```typescript
import chrono, { en } from 'chrono-node';
chrono.parse(...); // en.casual.parse()
chrono.parseDate(...); // en.casual.parseDate()
chrono.strict.parse(...); // strict English only
chrono.casual.parse(...); // casual English (default)
en.strict.parse(...); // strict English
en.casual.parse(...); // casual English
en.GB.parse(...); // UK-style English (DD/MM format)
```
--------------------------------
### Get Combined Debugging Tags
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
Returns a Set of combined debugging tags from both start and end components of a parsed result.
```typescript
tags(): Set
```
--------------------------------
### Accessing the index of a parsed result
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
The `index` field indicates the starting position of the matched text within the input string. This example shows how to log the index of the first parsed result.
```typescript
const text = "I have a meeting tomorrow at 3pm";
const results = chrono.parse(text);
console.log(results[0].index); // 22 (position of "tomorrow")
```
--------------------------------
### Extracting date range from parsed result
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
When a parsed result represents a date/time range, the `end` field is present. This example demonstrates how to extract the start and end dates of a range using `start.date()` and `end.date()`.
```typescript
import chrono from 'chrono-node';
const results = chrono.parse("Sep 12-13");
if (results[0].end) {
const startDate = results[0].start.date();
const endDate = results[0].end.date();
console.log(`Range: ${startDate} to ${endDate}`);
}
```
--------------------------------
### Get Specific Date for DST Calculation
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/calculation-utilities.md
Helper functions to retrieve specific dates within a month, useful for calculating Daylight Saving Time start and end points. These functions determine dates based on the day of the week and occurrence within the month.
```typescript
function getLastWeekdayOfMonth(
year: number,
month: Month,
weekday: Weekday,
hour: number
): Date
function getNthWeekdayOfMonth(
year: number,
month: Month,
weekday: Weekday,
n: number,
hour: number
): Date
```
--------------------------------
### Custom Locale Directory Structure
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/locales.md
Illustrates the expected file and directory structure for a new custom locale. This includes the main index file, configuration, constants, parsers, and refiners.
```bash
src/locales/xx/
├── index.ts # Exports casual, strict, parse(), parseDate()
├── configuration.ts # XXDefaultConfiguration
├── constants.ts # Locale-specific constants
├── parsers/
│ ├── XXMonthNameParser.ts
│ ├── XXTimeExpressionParser.ts
│ └── ...
└── refiners/
├── XXMergeDateTimeRefiner.ts
└── ...
```
--------------------------------
### Use Casual Chrono Instance
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
The `casual` instance is pre-configured for parsing informal English expressions. You can use it directly or clone it for customization. It exposes the number of parsers and refiners it uses.
```typescript
import chrono from 'chrono-node';
// These are equivalent:
chrono.parse('tomorrow');
chrono.casual.parse('tomorrow');
// Access parsers/refiners directly
console.log(chrono.casual.parsers.length); // 25+ parsers
console.log(chrono.casual.refiners.length); // 10+ refiners
// Customize the instance
const custom = chrono.casual.clone();
custom.parsers.push(myCustomParser);
```
--------------------------------
### Import Main Module
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
Import the Chrono library using its default export.
```typescript
import chrono from 'chrono-node';
```
```typescript
import * as chrono from 'chrono-node';
```
--------------------------------
### Build Commands for Chrono
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
These commands are used to build the Chrono package. They cover full builds, CommonJS-only, and ECMAScript-only builds, as well as running tests and benchmarks.
```bash
npm run build # Full build (CJS + ESM)
```
```bash
npm run build-cjs # CommonJS only
```
```bash
npm run build-esm # ECMAScript only
```
```bash
npm test # Run Jest tests
```
```bash
npm run benchmark # Performance benchmarks
```
--------------------------------
### Work with Component Certainty
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/GUIDE.md
Access parsed date components and check their certainty using `isCertain`. Get implied values using `get`, which returns the current or default value if not explicitly mentioned.
```typescript
import chrono from 'chrono-node';
const results = chrono.parse('Sep 12');
const components = results[0].start;
// Check what was explicitly mentioned
console.log(components.isCertain('month')); // true (Sep)
console.log(components.isCertain('day')); // true (12)
console.log(components.isCertain('year')); // false (not mentioned)
// Get values (certain or implied)
console.log(components.get('year')); // Current year (implied)
console.log(components.get('hour')); // 12 (implied default)
```
--------------------------------
### English Locale - Strict vs Casual
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/locales.md
Demonstrates the difference between strict and casual parsing modes in the English locale, highlighting recognized and unrecognized expressions.
```APIDOC
## English (en) - Strict vs Casual
```typescript
import { en } from 'chrono-node';
// Casual mode (default) - recognizes informal expressions
en.casual.parseDate('today'); // Returns date
en.casual.parseDate('tomorrow'); // Returns date
en.casual.parseDate('next Friday'); // Returns date
// Strict mode - only formal date patterns
en.strict.parseDate('today'); // null (not recognized)
en.strict.parseDate('tomorrow'); // null (not recognized)
en.strict.parseDate('2016-07-01'); // Recognized
en.strict.parseDate('Jul 01 2016'); // Recognized
```
```
--------------------------------
### Get component value (certain or implied)
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
Use get() to retrieve the value of any date/time component, whether it was explicitly stated or inferred from context. Returns null if the component is completely unknown. Note that certain components like 'millisecond' default to 0 if implied.
```typescript
import chrono from 'chrono-node';
const results = chrono.parse('tomorrow at 3pm');
const components = results[0].start;
console.log(components.get('day')); // Tomorrow's day number
console.log(components.get('month')); // Tomorrow's month (1-12)
console.log(components.get('year')); // Current year
console.log(components.get('hour')); // 15 (3pm in 24-hour)
console.log(components.get('minute')); // 0 (implied)
console.log(components.get('meridiem')); // 1 (PM)
// For unknown components
const unknownValue = components.get('millisecond');
// Returns 0 (implied default) - not null in this case
// Try a component that might not be set
const weekday = components.get('weekday');
// Returns the implied weekday if day was set, or null if completely unknown
```
--------------------------------
### Build Chrono Project
Source: https://github.com/wanasit/chrono/blob/master/README.md
Build the Chrono project using Webpack. This command generates the distributable files in the `dist` directory.
```bash
$ npm run build
```
--------------------------------
### casual
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
Provides a pre-configured Chrono instance specifically for casual English parsing. This instance is the default used by the `parse()` and `parseDate()` functions and can be cloned for custom configurations.
```APIDOC
## casual
### Description
Pre-configured Chrono instance for casual English parsing (default).
Equivalent to: `new Chrono(enConfiguration.createCasualConfiguration())`
### Features
- Recognizes informal expressions ("today", "tomorrow", "next Friday")
- Handles natural language phrasing
- Includes full date/time pattern support
- Default for `parse()` and `parseDate()`
### Usage Example
```javascript
import chrono from 'chrono-node';
// These are equivalent:
chrono.parse('tomorrow');
chrono.casual.parse('tomorrow');
// Access parsers/refiners directly
console.log(chrono.casual.parsers.length); // 25+ parsers
console.log(chrono.casual.refiners.length); // 10+ refiners
// Customize the instance
const custom = chrono.casual.clone();
custom.parsers.push(myCustomParser);
```
```
--------------------------------
### Chrono Constructor
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/chrono.md
Creates a new Chrono instance. You can provide a custom configuration object to specify parsers and refiners, or use the default configuration.
```APIDOC
## Chrono(configuration?: Configuration)
### Description
Creates a new Chrono instance with a given configuration.
### Method
Constructor
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **configuration** (Configuration) - Optional - An object with `parsers: Parser[]` and `refiners: Refiner[]`.
### Properties
- `parsers: Array` - Array of parser instances (can be modified)
- `refiners: Array` - Array of refiner instances (can be modified)
### Example
```typescript
import { Chrono, Parser, Refiner } from 'chrono-node';
// Create with default configuration
const chrono = new Chrono();
// Create with custom configuration
const customConfig = {
parsers: [...defaultParsers, myCustomParser],
refiners: [...defaultRefiners, myCustomRefiner]
};
const customChrono = new Chrono(customConfig);
```
```
--------------------------------
### Importing Chrono Locales
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/configuration.md
Demonstrates how to import specific locales to reduce bundle size. Import the full bundle or specific language packs as needed.
```typescript
// Full bundle (~150KB)
import chrono from 'chrono-node';
```
```typescript
// Minimal bundle (~50KB) - English only
import chrono from 'chrono-node/en';
```
```typescript
// Medium bundle (~80KB) - English + French
import en from 'chrono-node/en';
import fr from 'chrono-node/fr';
```
--------------------------------
### Run Chrono Unit Tests
Source: https://github.com/wanasit/chrono/blob/master/README.md
Execute the unit tests for the Chrono library using npm. Tests are based on Jest.
```bash
# Run the test
$ npm run test
```
--------------------------------
### Pre-configured Chrono Instances
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/00-START-HERE.txt
Utilize pre-configured instances of Chrono for different parsing needs, such as casual, strict, or locale-specific parsing.
```javascript
chrono.casual English casual (default, accepts "tomorrow" etc)
```
```javascript
chrono.strict English strict (formal patterns only)
```
```javascript
en.casual, en.strict English with options
```
```javascript
en.GB UK English (DD/MM format)
```
```javascript
fr, ja, de, pt, nl, zh, ru ... Other locales
```
--------------------------------
### Parse Function Return Value Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/errors.md
Illustrates that chrono.parse() always returns an array, which will be empty if no matches are found. An empty array does not signify an error.
```typescript
import chrono from 'chrono-node';
const results = chrono.parse('no dates here');
console.log(Array.isArray(results)); // true
console.log(results.length); // 0 (not null)
if (results.length > 0) {
// Process results
} else {
// No dates found
}
```
--------------------------------
### Parse Italian Dates
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/locales.md
Demonstrates parsing Italian date and time expressions using the `it` locale, including month names and 'domani' for tomorrow.
```typescript
import { it } from 'chrono-node';
it.parseDate('15 giugno 2024'); // Supported: Italian month names
it.parseDate('domani'); // Supported: "tomorrow"
```
--------------------------------
### ParsedResult
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/types.md
Represents a single parsed date/time result from input text. It contains information about the matched text, its position, and the parsed start and end components.
```APIDOC
## ParsedResult
### Description
A parsed date/time result extracted from input text.
### Fields
- **refDate** (Date) - Required - The reference date used for parsing (read-only)
- **index** (number) - Required - Starting position of the matched text in the input string (read-only)
- **text** (string) - Required - The matched text from the input (read-only)
- **start** (ParsedComponents) - Required - Parsed components for the start date/time (read-only)
- **end** (ParsedComponents) - Optional - Parsed components for the end date/time if a range was detected (read-only)
### Methods
- **date()** - Date - Creates a JavaScript Date object from the `start` components
- **tags()** - Set - Returns debugging tags from both `start` and `end`
### Example
```typescript
const results = chrono.parse("Tomorrow at 3pm");
if (results.length > 0) {
const result = results[0];
console.log(result.index); // 0
console.log(result.text); // "Tomorrow at 3pm"
console.log(result.start.get("day")); // Tomorrow's day
console.log(result.date()); // JavaScript Date object
}
```
```
--------------------------------
### Basic Date and Time Parsing
Source: https://github.com/wanasit/chrono/blob/master/README.md
Use `chrono.parseDate` for direct date parsing or `chrono.parse` for more detailed results. Both accept natural language strings.
```javascript
import * as chrono from 'chrono-node';
chrono.parseDate('An appointment on Sep 12-13');
// Fri Sep 12 2014 12:00:00 GMT-0500 (CDT)
chrono.parse('An appointment on Sep 12-13');
/* [{
index: 18,
text: 'Sep 12-13',
start: ...
}] */
```
--------------------------------
### Accessing the text of a parsed result
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
The `text` field contains the substring recognized as a date/time mention. This example logs the recognized text for the first parsed result.
```typescript
const results = chrono.parse("I have a meeting tomorrow at 3pm");
console.log(results[0].text); // "tomorrow at 3pm"
```
--------------------------------
### clone()
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/chrono.md
Creates a shallow copy of the current Chrono instance, allowing for independent customization of parsers and refiners for specific tasks without altering the original instance.
```APIDOC
## clone() API
### Description
Creates a shallow copy of the current Chrono instance, allowing for independent customization of parsers and refiners for specific tasks without altering the original instance.
### Method Signature
```typescript
clone(): Chrono
```
### Parameters
#### Path Parameters
* None
#### Query Parameters
* None
#### Request Body
* None
### Returns
`Chrono` - A new Chrono instance with copied configuration
### Use Case
When you want to customize a configuration for specific parsing tasks without affecting the original instance.
### Example
```typescript
import { en } from 'chrono-node';
// Start with English casual parser
const customChrono = en.casual.clone();
// Add a custom parser
customChrono.parsers.push({
pattern: () => /\bChristmas\b/i,
extract: (context, match) => ({
day: 25,
month: 12
})
});
// Use the custom parser
const date = customChrono.parseDate("I'll arrive on Christmas");
// Fri Dec 25 2024 12:00:00 GMT+0000
// Original en.casual is unchanged
const dateWithoutCustom = en.casual.parseDate("I'll arrive on Christmas");
// Returns null (doesn't recognize "Christmas")
```
```
--------------------------------
### ParsedComponents Example Usage
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/types.md
Illustrates how to use ParsedComponents methods to check the certainty of date components, retrieve their values (certain or implied), and create a Date object.
```typescript
const results = chrono.parse("Sep 12");
const components = results[0].start;
console.log(components.isCertain("month")); // true (9)
console.log(components.isCertain("day")); // true (12)
console.log(components.isCertain("year")); // false (implied)
console.log(components.get("year")); // Current year (implied)
console.log(components.date()); // Sep 12, 12:00 PM
```
--------------------------------
### Create Chrono Instance
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/chrono.md
Instantiate the Chrono class with default or custom configurations. Custom configurations allow for the inclusion of additional parsers and refiners.
```typescript
import { Chrono, Parser, Refiner } from 'chrono-node';
// Create with default configuration
const chrono = new Chrono();
// Create with custom configuration
const customConfig = {
parsers: [...defaultParsers, myCustomParser],
refiners: [...defaultRefiners, myCustomRefiner]
};
const customChrono = new Chrono(customConfig);
```
--------------------------------
### Parse Date with Chrono
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/GUIDE.md
Use Chrono to parse natural language strings into JavaScript Date objects. This snippet shows how to get the first parsed result.
```typescript
import chrono from 'chrono-node';
// Parse and get first result as Date
const date = chrono.parseDate('tomorrow at 3pm');
console.log(date); // Tomorrow at 3:00 PM
```
--------------------------------
### Get Backward Days to Weekday
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/calculation-utilities.md
Returns the number of days backward to the previous occurrence of a specified weekday. The result will always be a negative number between -6 and 0.
```typescript
function getBackwardDaysToWeekday(refDate: Date, weekday: Weekday): number
```
--------------------------------
### Create Custom Chrono Configuration
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/configuration.md
Instantiate Chrono with a custom configuration object, specifying parsers and refiners. Useful for adding specific parsing logic.
```typescript
import { Chrono, Configuration } from 'chrono-node';
import { ISOFormatParser } from 'chrono-node';
const customConfig: Configuration = {
parsers: [
new ISOFormatParser(),
// Add more parsers...
],
refiners: [
// Add refiners...
]
};
const chrono = new Chrono(customConfig);
const results = chrono.parse('2024-06-15');
```
--------------------------------
### Get Days Forward to Weekday
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/calculation-utilities.md
Returns the number of days forward to the next occurrence of a specified weekday. The result will always be a positive number between 0 and 6.
```typescript
function getDaysForwardToWeekday(refDate: Date, weekday: Weekday): number
```
--------------------------------
### Import Chrono Node Package (CommonJS)
Source: https://github.com/wanasit/chrono/blob/master/README.md
Import the chrono-node library using require for use in a CommonJS environment (Node.js).
```javascript
const chrono = require('chrono-node');
// or `import chrono from 'chrono-node'` for ECMAScript
```
--------------------------------
### Core Classes in Chrono
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/README.md
Illustrates the core classes of the Chrono library, including the main parsing engine 'Chrono' and the 'ParsingContext' used for parsing and refinement.
```typescript
// Main parsing engine
Chrono {
constructor(configuration?: Configuration)
parse(text, ref?, option?): ParsedResult[]
parseDate(text, ref?, option?): Date | null
clone(): Chrono
}
// Context (passed to parsers/refiners)
ParsingContext {
text: string
option: ParsingOption
reference: ReferenceWithTimezone
createParsingComponents(...)
createParsingResult(...)
debug(block)
}
// For customization
Parser = { pattern(context), extract(context, match) }
Refiner = { refine(context, results) }
```
--------------------------------
### Parse Finnish Date and Time Expressions
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/locales.md
Shows how to parse Finnish date formats, including month names and the word for 'tomorrow'. The Finnish locale must be imported.
```typescript
import { fi } from 'chrono-node';
fi.parseDate('15. kesäkuuta 2024'); // Supported: Finnish month names
fi.parseDate('huomenna'); // Supported: "tomorrow"
```
--------------------------------
### Parse Multiple Results with Chrono
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/GUIDE.md
Parse natural language strings with Chrono to retrieve all possible results along with their metadata. This includes text, start, and end times.
```typescript
import chrono from 'chrono-node';
// Parse and get all results with metadata
const results = chrono.parse('meeting on Sep 12-13');
results.forEach(result => {
console.log(result.text); // "Sep 12-13"
console.log(result.start.date()); // Sep 12, 12:00 PM
console.log(result.end?.date()); // Sep 13, 12:00 PM
});
```
--------------------------------
### Parse Date Return Value Example
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/errors.md
Demonstrates how parseDate() returns a Date object for valid input and null for invalid input. Always check the return value before using it.
```typescript
import chrono from 'chrono-node';
// Valid input
const date1 = chrono.parseDate('tomorrow');
console.log(date1); // Date object
// Invalid input
const date2 = chrono.parseDate('Lorem ipsum dolor');
console.log(date2); // null
// Check result before using
const date = chrono.parseDate(userInput);
if (date) {
console.log(date.toISOString());
} else {
console.log('No date found');
}
```
--------------------------------
### Package Exports Configuration
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
Defines the entry points for importing the Chrono-Node package, supporting main module and locale-specific imports for both CommonJS and ESM.
```json
{
"exports": {
".": {
"require": "./dist/cjs/index.js",
"import": "./dist/esm/index.js"
},
"./*": {
"require": "./dist/cjs/locales/*/index.js",
"import": "./dist/esm/locales/*/index.js"
},
"./*/*": {
"require": "./dist/cjs/locales/*/*/index.js",
"import": "./dist/esm/locales/*/*/index.js"
}
}
}
```
--------------------------------
### ParsingResult Interface
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
The ParsingResult interface defines the structure of a single date/time mention found in the input text. It includes information about the matched text, its position, and its start and end components.
```APIDOC
## ParsingResult Interface
Represents a single date/time mention in the input text.
### Fields
- **index** (number) - The starting position of the matched text within the input string (0-based).
- **text** (string) - The substring of the input that was recognized as a date/time mention.
- **start** (ParsedComponents) - Parsed date/time components for the start of the range (or the exact date if not a range).
- **end** (ParsedComponents) - Optional parsed date/time components for the end of a date/time range. When present, `start` and `end` represent a range.
```
--------------------------------
### ParsedComponents Interface Definition
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/types.md
Defines the structure for parsed date/time components, offering methods to check certainty, retrieve values, create a Date object, and get debugging tags.
```typescript
interface ParsedComponents {
isCertain(component: Component): boolean;
get(component: Component): number | null;
date(): Date;
tags(): Set;
}
```
--------------------------------
### Create a Custom Refiner in Chrono-Node
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parser-refiner-abstractions.md
This template demonstrates how to create a custom refiner. Implement the `refine` method to filter, modify, or merge the results obtained from parsers. This is useful for applying specific logic to standardize or correct extracted date-time information.
```typescript
import { Refiner, ParsingContext } from 'chrono-node';
import { ParsingResult } from 'chrono-node';
const myRefiner: Refiner = {
refine(context: ParsingContext, results: ParsingResult[]): ParsingResult[] {
// Filter, modify, or merge results
return results.filter(result => {
// Apply custom logic
return true; // Keep result
});
}
};
// Usage
const chrono = new Chrono({
parsers: [],
refiners: [myRefiner]
});
```
--------------------------------
### TypeScript Compiler Options Recommendation
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/entry-points.md
Recommended TypeScript compiler options for optimal integration with Chrono-Node, particularly for module resolution and target ECMAScript version.
```json
{
"compilerOptions": {
"moduleResolution": "node16",
"target": "ES2020"
}
}
```
--------------------------------
### Create Parsing Result
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/chrono.md
Constructs a ParsingResult object, which represents a parsed date or time range. It takes the starting index, matched text or end index, and optional start/end components.
```typescript
createParsingResult(
index: number,
textOrEndIndex: number | string,
startComponents?: { [c in Component]?: number } | ParsingComponents,
endComponents?: { [c in Component]?: number } | ParsingComponents
): ParsingResult
```
--------------------------------
### ReferenceWithTimezone Instance Methods
Source: https://github.com/wanasit/chrono/blob/master/_autodocs/api-reference/parsing-components.md
Provides methods for interacting with the ReferenceWithTimezone object, including retrieving dates with adjusted timezones, system timezone adjustments, and the reference timezone offset.
```APIDOC
## ReferenceWithTimezone Instance Methods
### getDateWithAdjustedTimezone()
Returns a JS date with local time matching the reference timezone.
### getSystemTimezoneAdjustmentMinute(date?: Date)
Returns timezone offset difference in minutes.
### getTimezoneOffset()
Returns the reference timezone offset.
```