Chrono

A natural language date parser in Javascript

README

Chrono (v2)


A natural language date parser in Javascript.

Build Status
Coverage Status

It is designed to handle most date/time format and extract information from any given text:

_Today_, _Tomorrow_, _Yesterday_, _Last Friday_, etc
_17 August 2013 - 19 August 2013_
_This Friday from 13:00 - 16.00_
_5 days ago_
_2 weeks from now_
_Sat Aug 17 2013 18:40:39 GMT+0900 (JST)_
_2014-11-30T08:15:30-05:30_

Installation


With npm:
  1. ```bash
  2. $ npm install --save chrono-node
  3. ```
    
  1. ```javascript
  2. import * as chrono from 'chrono-node';

  3. chrono.parseDate('An appointment on Sep 12-13');
  4. ```
For Node.js:
  1. ```javascript
  2. const chrono = require('chrono-node');

  3. // or `import chrono from 'chrono-node'` for ECMAScript
  4. ```

What's changed in the v2

For Users
Chrono’s default now handles only international English. While in the previous version, it tried to parse with all known languages.
The current fully supported languages are en, ja, fr, nl and ru (de, pt, and zh.hant are partially supported).

For contributors and advanced users
The project is rewritten in TypeScript
New Parser and Refiner interface
New source code structure. All parsers, refiners, and configuration should be under a locale directory (See. locales/en)

Note: v1.x.x will still be supported for the time being.

Usage


Simply pass a string to functions chrono.parseDate or chrono.parse.

  1. ```javascript
  2. import * as chrono from 'chrono-node';

  3. chrono.parseDate('An appointment on Sep 12-13');
  4. // Fri Sep 12 2014 12:00:00 GMT-0500 (CDT)
  5.     
  6. chrono.parse('An appointment on Sep 12-13');
  7. /* [{
  8.     index: 18,
  9.     text: 'Sep 12-13',
  10.     start: ...
  11. }] */
  12. ```

For more advanced usage, here is the typescript definition of the parse function:
  1. ```typescript
  2. parse(text: string, ref?: ParsingReference, option?: ParsingOption): ParsedResult[] {...}
  3. ```

Parsing Reference (Date / Timezone)


Today's "Friday" is different from last month's "Friday".
The meaning of the referenced dates depends on when and where they are mentioned.
Chrono lets you define the reference as Date or ParsingReference object:

  1. ```javascript
  2. // (Note: the exmaples run on JST timezone)

  3. chrono.parseDate('Friday', new Date(2012, 8 - 1, 23));
  4. // Fri Aug 24 2012 12:00:00 GMT+0900 (JST)

  5. chrono.parseDate('Friday', new Date(2012, 8 - 1, 1));
  6. // Fri Aug 03 2012 12:00:00 GMT+0900 (JST)

  7. chrono.parseDate("Friday at 4pm", {
  8.     // Wed Jun 09 2021 21:00:00 GMT+0900 (JST)
  9.     // = Wed Jun 09 2021 07:00:00 GMT-0500 (CDT)
  10.     instant: new Date(1623240000000),
  11.     timezone: "CDT",
  12. })
  13. // Sat Jun 12 2021 06:00:00 GMT+0900 (JST)
  14. // = Fri Jun 11 2021 16:00:00 GMT-0500 (CDT)
  15. ```

ParsingReference

instant?: Date The instant when the input is written or mentioned
timezone?: string | number The timezone where the input is written or mentioned.
  Support minute-offset (number) and timezone name (e.g. "GMT", "CDT")

Parsing Options


forwardDate (boolean) to assume the results should happen after the reference date (forward into the future)

  1. ```javascript
  2. const referenceDate = new Date(2012, 7, 25);
  3. // Sat Aug 25 2012 00:00:00 GMT+0900 -- The reference date was Saturday

  4. chrono.parseDate('Friday', referenceDate);
  5. // Fri Aug 24 2012 12:00:00 GMT+0900 (JST) -- The day before was Friday

  6. chrono.parseDate('Friday', referenceDate, { forwardDate: true });
  7. // Fri Aug 31 2012 12:00:00 GMT+0900 (JST) -- The following Friday
  8. ```

Parsed Results and Components


ParsedResult

refDate: Date The reference date of this result
index: number The location within the input text of this result  
text: string  The text this result that appears in the input
start: ParsedComponents The parsed date components as a ParsedComponents object
end?: ParsedComponents  Similar to start
date: () => Date Create a javascript Date

ParsedComponents

get: (c: Component) => number | null    Get known or implied value for the component
isCertain: (c: Component) => boolean    Check if the component has a known value
date: () => Date    Create a javascript Date

For example:
  1. ```js
  2. const results = chrono.parse('I have an appointment tomorrow from 10 to 11 AM');

  3. results[0].index;     // 22
  4. results[0].text;      // 'tomorrow from 10 to 11 AM'
  5. results[0].refDate;   // Sat Dec 13 2014 21:50:14 GMT-0600 (CST)

  6. // `start` is Sat Dec 14 2014 10:00:00
  7. results[0].start.get('day');    // 14 (the 14th, the day after refDate)
  8. results[0].start.get('month');  // 12 (or December)
  9. results[0].start.get('hour');   // 10
  10. results[0].start.date();        // Sun Dec 14 2014 10:00:00 GMT-0600 (CST)

  11. ...
  12. results[0].end.date();  // Sun Dec 14 2014 11:00:00 GMT-0600 (CST)
  13. ```

Strict vs Casual configuration


Chrono comes with strict mode that parse only formal date patterns.

  1. ```js
  2. // 'strict' mode
  3. chrono.strict.parseDate('Today');       // null
  4. chrono.strict.parseDate('Friday');      // null
  5. chrono.strict.parseDate('2016-07-01');  // Fri Jul 01 2016 12:00:00 ...
  6. chrono.strict.parseDate('Jul 01 2016'); // Fri Jul 01 2016 12:00:00 ...

  7. // 'casual' mode (default)
  8. chrono.parseDate('Today');              // Thu Jun 30 2016 12:00:00 ...
  9. chrono.casual.parseDate('Friday');      // Fri Jul 01 2016 12:00:00 ...
  10. chrono.casual.parseDate('2016-07-01');  // Fri Jul 01 2016 12:00:00 ...
  11. chrono.casual.parseDate('Jul 01 2016'); // Fri Jul 01 2016 12:00:00 ...
  12. ```

Locales


By default, Chrono is configured to handle only international English.
This differs from the previous version of Chrono that would try all locales by default.

There are several locales supported contributed by multiple developers under ./locales directory.

  1. ```js
  2. // default English (US)
  3. chrono.parseDate('6/10/2018');    

  4. chrono.en.parseDate('6/10/2018');       // June 10th, 2018
  5. chrono.en.GB.parseDate('6/10/2018');    // October 6th, 2018

  6. chrono.ja.parseDate('昭和64年1月7日');
  7. ```

Current supported locale options are: en, ja, fr, nl and ru (de, pt, and zh.hant are partially supported).

Customize Chrono


Chrono’s extraction pipeline configuration consists of parsers: Parser[] and refiners: Refiner[].

First, each parser independently extracts patterns from input text input and create parsing results  (ParsingResult).
Then, the parsing results are combined, sorted, and refined with the refiners. In the refining phase, the results can be filtered-out, merged, or attached with additional information.

Parser


  1. ```typescript
  2. interface Parser {
  3.     pattern: (context: ParsingContext) => RegExp,
  4.     extract: (context: ParsingContext, match: RegExpMatchArray) =>
  5.         (ParsingComponents | ParsingResult | {[c in Component]?: number} | null)
  6. }
  7. ```

Parser is a module for low-level pattern-based parsing.
Ideally, each parser should be designed to handle a single specific date format.

User can create a new parser for supporting new date formats or languages
by providing RegExp pattern pattern() and extracting result or components from the RegExp match extract().

  1. ```javascript
  2. const custom = chrono.casual.clone();
  3. custom.parsers.push({
  4.     pattern: () => { return /\bChristmas\b/i },
  5.     extract: (context, match) => {
  6.         return {
  7.             day: 25, month: 12
  8.         }
  9.     }
  10. });

  11. custom.parseDate("I'll arrive at 2.30AM on Christmas night");
  12. // Wed Dec 25 2013 02:30:00 GMT+0900 (JST)
  13. // 'at 2.30AM on Christmas'
  14. ```

Refiner


  1. ```typescript
  2. interface Refiner {
  3.     refine: (context: ParsingContext, results: ParsingResult[]) => ParsingResult[]
  4. }
  5. ```

Refiner is a higher level module for improving or manipulating the results. User can add a new type of refiner to customize Chrono's results or to add some custom logic to Chrono.

  1. ```javascript
  2. const custom = chrono.casual.clone();
  3. custom.refiners.push({
  4.     refine: (context, results) => {
  5.         // If there is no AM/PM (meridiem) specified,
  6.         //  let all time between 1:00 - 4:00 be PM (13.00 - 16.00)
  7.         results.forEach((result) => {
  8.             if (!result.start.isCertain('meridiem') &&
  9.                 result.start.get('hour') >= 1 && result.start.get('hour') < 4) {

  10.                 result.start.assign('meridiem', 1);
  11.                 result.start.assign('hour', result.start.get('hour') + 12);
  12.             }
  13.         });
  14.         return results;
  15.     }
  16. });

  17. // This will be parsed as PM.
  18. // > Tue Dec 16 2014 14:30:00 GMT-0600 (CST)
  19. custom.parseDate("This is at 2.30");

  20. // Unless the 'AM' part is specified
  21. // > Tue Dec 16 2014 02:30:00 GMT-0600 (CST)
  22. custom.parseDate("This is at 2.30 AM");
  23. ```

In the example, the custom refiner assigns PM to parsing results with ambiguous meridiem.
The refine method of the refiner class will be called with parsing results (from parsers or other previous refiners).
The method must return an array of the new results (which, in this case, we modified those results in place).

More documentation


Checkout the Typescript Documentation in the project's Github page.

Development Guides


This guide explains how to set up chrono project for prospective contributors.

  1. ```bash
  2. # Clone and install library
  3. $ git clone https://github.com/wanasit/chrono.git chrono
  4. $ cd chrono
  5. $ npm install

  6. ```

Parsing date from text is complicated. A small change can have effects on unexpected places.
So, Chrono is a heavily tested library.
Commits that break a test shouldn't be allowed in any condition.

Chrono's unit testing is based-on Jest.

  1. ```bash
  2. # Run the test
  3. $ npm run test

  4. # Run the test in watch mode
  5. $ npm run watch
  6. ```

Chrono's source files is in src directory.
The built bundle (dist/*) is created by running Webpack via the following command

  1. ```bash
  2. $ npm run build
  3. ```