chrono-node

repository·master·Indexed 26 days ago

https://github.com/wanasit/chrono

A natural language date parser for JavaScript and TypeScript that extracts date and time information from unstructured text. It supports relative terms like 'tomorrow', various international formats, and provides both 'casual' and 'strict' parsing modes. The library includes support for multiple locales (including English, German, Spanish, French, and Japanese) and allows for extensibility via custom Parsers and Refiners.

Tokens
7.7K
Snippets
10
Records
76
Agent score
89%

What's inside chrono-node

  1. Parse using specific Locales

    master

    By default, Chrono uses international English. To parse in other languages, use the locale-specific exports. Supported languages include fi, fr, it, ja, nl, ru, uk, and vi, with partial support for de, es, pt, sv, zh.hans, and zh.hant.

    Note on Node.js/Intl: If your Node.js runtime has the Intl module disabled, importing all locales might cause errors. To avoid this, import only the specific locale you need.

  2. Set up the Chrono development environment

    master

    To contribute to Chrono, clone the repository and install dependencies using npm.

    # Clone and install library
    $ git clone https://github.com/wanasit/chrono.git chrono
    $ cd chrono
    $ npm install
    $ git clone https://github.com/wanasit/chrono.git chrono
    $ cd chrono
    $ npm install
  3. Configure parsing with ParsingOptions

    master

    You can pass an options object to parse or parseDate to modify behavior.

    Options:

    • forwardDate (boolean): If true, assumes results should occur after the reference date (searching into the future).
    • timezones (object): Override or add custom mappings between timezone abbreviations and offsets. Can be a simple mapping { XYZ: -180 } or an ambiguous mapping object for handling Daylight Savings Time (DST).
  4. Customize Chrono with a custom Refiner

    master

    You can manipulate or improve parsing results by adding a Refiner to the refiners array. Refiners operate at a higher level than parsers; they receive the combined results from all parsers (and previous refiners) and can filter, merge, or modify them.

    A refiner must implement:

    • refine(context, results): A function that accepts the ParsingContext and an array of ParsingResult[], and returns a modified or new array of ParsingResult[].

    Note: You can modify the results in place or return a new array.

    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");
  5. Set a Parsing Reference (Date/Timezone)

    master

    When parsing relative dates (like "Friday"), you can provide a ParsingReference to define the context of "now".

    ParsingReference properties:

    • instant?: Date: The instant when the input is written or mentioned.
    • timezone?: string | number: The timezone where the input is written or mentioned. Supports timezone names (e.g., "CDT") or minute-offsets (e.g., -180).
    // Using a Date object as reference
    chrono.parseDate('Friday', new Date(2012, 8 - 1, 23)); 
    
    // Using a ParsingReference object
    chrono.parseDate("Friday at 4pm", {
        instant: new Date(1623240000000), 
        timezone: "CDT",
    });
  6. Customize Chrono with a custom Parser

    master

    You can extend Chrono's parsing capabilities by adding a new Parser to the parsers array. A parser is a low-level module designed to handle specific date formats using a regular expression.

    To implement a parser, you must provide:

    1. pattern(): A function that returns a RegExp used to identify the date pattern in the input text.
    2. extract(): A function that takes the ParsingContext and the RegExpMatchArray to return ParsingComponents, a ParsingResult, or a mapping of components to values.

    It is recommended to use chrono.casual.clone() or chrono.strict.clone() to avoid mutating the original instances.

    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'
  7. Use chrono.parseDate() to extract a single date

    master

    Use chrono.parseDate(text) to parse a natural language string and return a Javascript Date object. This is the simplest way to get a single date from text.

    import * as chrono from 'chrono-node';
    
    chrono.parseDate('An appointment on Sep 12-13'); 
  8. Use chrono.parse() to extract detailed parsing results

    master

    Use chrono.parse(text, [ref], [option]) to get an array of ParsedResult objects. This provides metadata like the text index, the original text, and specific date components (start/end).

    Signature: parse(text: string, ref?: ParsingReference, option?: ParsingOption): ParsedResult[]

    import * as chrono from 'chrono-node';
    
    chrono.parse('An appointment on Sep 12-13');
    /* [{ 
        index: 18,
        text: 'Sep 12-13',
        start: ...
    }] */
  9. Use Strict vs Casual parsing modes

    master

    Chrono provides two modes for parsing:

    • chrono.casual: The default mode. It parses both formal date patterns and natural language (e.g., "Today", "Friday").
    • chrono.strict: Only parses formal, unambiguous date patterns (e.g., "2016-07-01"). It will return null for natural language strings like "Today".
  10. Access ParsedResult and ParsedComponents

    master

    The chrono.parse method returns ParsedResult objects. Each result contains:

    • refDate: Date: The reference date used for this result.
    • index: number: The start index of the matched text.
    • text: string: The original text fragment.
    • start: ParsedComponents: The start date components.
    • end?: ParsedComponents: The end date components (if applicable).
    • date: () => Date: A function to create a Javascript Date from the result.

    ParsedComponents allows you to inspect specific parts of the date:

    • get(component: Component): number | null: Returns the value for a component (e.g., 'day', 'month', 'hour').
    • isCertain(component: Component): boolean: Checks if the component value is known or implied.
    • date(): Date: Returns the full Javascript Date object.
    const results = chrono.parse('I have an appointment tomorrow from 10 to 11 AM');
    
    results[0].start.get('day');    // 14
    results[0].start.get('month');  // 12
    results[0].start.get('hour');   // 10 
    results[0].start.date();        // Sun Dec 14 2014 10:00:00 ...