Is there a way to parse a relative date using Moment.js?

Moment.js is a very useful JavaScript library that provides many functions for managing date formatting.

To create a Moment object, you can parse a string simply moment("1995-12-25");or provide a format moment("12-25-1995", "MM-DD-YYYY");.

Another function allows us to use relative dates : moment("1995-12-25").fromNow() // 19 years ago.

However, I cannot find a way to parse such a relative date. When I try moment("19 years ago"), it just returns Invalid date, and it does not contain any token in order to format the date correctly.

Is there an easy way to do this? Or is this the missing feature to be offered on Github?

+4
source share
5 answers

The only way to do this is: moment().sub(19, 'years');

What you ask for implies "Natural Language Processing" , which is the domain of all computer science.

+4
source

Just found chrono to see if NLP was already implemented in momentjs. It looks like it handles NLP parsing for a date, which can be used to create datejs dates.

Just pass a string to the chrono.parseDate or chrono.parse function.

> var chrono = require('chrono-node')

> chrono.parseDate('An appointment on Sep 12-13') 
Fri Sep 12 2014 12:00:00 GMT-0500 (CDT)

And a quick example showing how this will work

the code

const moment = require('moment')
const chrono = require('chrono-node')

let now = moment()
console.log(now)
let yrsAgo = chrono.parseDate("19 years ago")
console.log(yrsAgo)
let yrsAgoMoment = moment(yrsAgo)
console.log(yrsAgoMoment)

Output

$node test.js
moment("2017-06-30T08:29:20.938")
1998-06-30T17:00:00.000Z
moment("1998-06-30T12:00:00.000")
+3
source
+1

:

moment.fn.parse = function(_relative, _format){
    var _modulo = moment.normalizeUnits(_format);
    return this.add(_relative, _modulo);
}

moment("30/08/2015", "DD/MM/YYYY").parse(-20, "years").format('DD/MM/YYYY'); // 30/08/1995
moment("30/08/2015", "DD/MM/YYYY").parse(-2, "week").format('DD/MM/YYYY'); // 16/08/2015
moment("30/08/2015", "DD/MM/YYYY").parse(-2, "d").format('DD/MM/YYYY'); // 28/08/2015
+1

I wrote the relative.time.parser plugin. The original intention was to analyze the relative time from graphite from / to , so I was only going to "reverse" in time.

I will also consider options for using NLP.

Thank you, Chris

+1
source

All Articles