admin管理员组

文章数量:1201048

Moment.js is a very usefull JavaScript library which provides many functions to manipulate date formatting.

In order to create a Moment object, it is possible to parse a string simply moment("1995-12-25"); or by providing format moment("12-25-1995", "MM-DD-YYYY");.

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

However, I can not 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 exist any token to properly format the date.

Is there an easy way to do this? Or is it a missing feature that should be suggested on Github?

Moment.js is a very usefull JavaScript library which provides many functions to manipulate date formatting.

In order to create a Moment object, it is possible to parse a string simply moment("1995-12-25"); or by providing format moment("12-25-1995", "MM-DD-YYYY");.

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

However, I can not 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 exist any token to properly format the date.

Is there an easy way to do this? Or is it a missing feature that should be suggested on Github?

Share Improve this question asked Jun 6, 2015 at 12:50 DelganDelgan 19.6k11 gold badges98 silver badges155 bronze badges
Add a comment  | 

7 Answers 7

Reset to default 12

Just found chrono wile looking to see if NLP had already been implemented in momentjs. It looks like it handles parsing NLP to a date, which can be used to create a momentjs date.

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

> 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 that would work

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")

The only way of doing this is moment().sub(19, 'years');

What you are asking imply a Natural language processing which is whole computer science field.

I wrote the plugin relative.time.parser. The original intent was to parse relative time from graphite from/until, so I was only going for the 'reverse' in time.

I will take a look at adding the 'NLP' use cases as well.

Thanks, Chris

There is a plugin which very recently appeared on github, which is a plugin to moment to allow this sort of parsing: https://github.com/cmaurer/relative.time.parser

I have not personally tried it, but I will shortly (found both it and this question while searching for the same thing).

You can do it easily using moment plus little logic. Here it is working perfectly

function parseSincUntilDate(dateStr, now = new Date()) {
  // inputs: 20 minutes ago, 7 hours from now, now, '', or UTC string
  if (moment(dateStr).isValid()) return moment(dateStr).toDate();
  const tokens = dateStr.split(' ');
  if (dateStr.includes('ago')) {
    return moment(now).subtract(tokens[0], tokens[1]).toDate();
  } else if (dateStr.includes('from now')) {
    return moment(now).add(tokens[0], tokens[1]).toDate();
  } else if (dateStr === 'now' || dateStr === '') {
    return new Date(now);
  }
  return moment(dateStr).toDate();
}
// to change relative date, pass it in second parameter

What about :

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

As of Moment.js 1.0.0 (October 2011) to current:

moment().add(7, 'days');
moment().subtract(1, 'seconds');

Works with years, quarters, months, weeks, days, hours, minutes, seconds, and milliseconds.

https://momentjs.com/docs/#/manipulating/add/

https://momentjs.com/docs/#/manipulating/subtract/

本文标签: javascriptIs there a way to parse a relative date using MomentjsStack Overflow