Elasticsearch Date Math Parser

1.0.6 · abandoned · verified Sun Apr 19

datemath-parser is a JavaScript library designed to parse date math expressions compatible with the Elasticsearch format. It takes expressions like `now+1h`, `now+1M/d`, or `2012-01-01||+1M/d` and returns an integer representing the timestamp in milliseconds. The current stable version is 1.0.6. This package appears to be largely unmaintained, with its last update occurring in 2018. While functional for its specific purpose, developers should be aware of its inactive development cycle when considering it for new projects or environments with strict maintenance requirements. It differentiates itself by adhering strictly to Elasticsearch's date math specification, making it a targeted solution for systems interacting with Elasticsearch date queries. Other, more actively maintained libraries, like `@elastic/datemath` or `date-fns` may offer broader date manipulation capabilities and better support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing various Elasticsearch-compatible date math expressions, including relative to 'now', with rounding, and using an explicit anchor date. It also shows how to provide a custom 'now' value and control rounding behavior.

const parser = require('datemath-parser');

// Parse a simple expression relative to 'now'
let expression1 = 'now+1h';
let timestamp1 = parser.parse(expression1);
console.log(`'${expression1}' resolves to: ${new Date(timestamp1).toISOString()} (timestamp: ${timestamp1})`);

// Parse an expression with rounding
let expression2 = 'now/d'; // round to the beginning of the day
let timestamp2 = parser.parse(expression2);
console.log(`'${expression2}' resolves to: ${new Date(timestamp2).toISOString()} (timestamp: ${timestamp2})`);

// Parse an expression with an explicit anchor date
let expression3 = '2023-01-01||+1M/d'; // January 1st, 2023 plus one month, rounded to day
let timestamp3 = parser.parse(expression3);
console.log(`'${expression3}' resolves to: ${new Date(timestamp3).toISOString()} (timestamp: ${timestamp3})`);

// Demonstrate parsing with a custom 'now' date and rounding up
const customNow = new Date('2024-03-15T10:30:00Z');
let expression4 = 'now+2d/w'; // 2 days from customNow, rounded up to the end of the week
let timestamp4 = parser.parse(expression4, customNow.getTime(), true); // Pass custom now as milliseconds, roundUp = true
console.log(`'${expression4}' (with custom now ${customNow.toISOString()}) resolves to: ${new Date(timestamp4).toISOString()} (timestamp: ${timestamp4})`);

view raw JSON →