Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 538
Delgan Avatar asked Jun 06 '15 12:06

Delgan


People also ask

How do you compare dates with moments?

Compare two dates using Moment.js has a diff() method, which gives the difference between two dates in years, months, days, hours, minutes, seconds, milliseconds, etc. We can use the second unit in our case to find the difference between the two dates. Before using the Moment. js methods, make sure to include Moment.

How do you parse time in a moment?

js parsing date and time. We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console.

How can I get previous date in moment?

Just like this: moment(). subtract(1, 'days') . It will give you the previous day with the same exact current time that is on your local pc. Save this answer.

Is MomentJS still used?

MomentJS is a widely used time and date formatting and calculation library.

Is MomentJS deprecated?

js . This library helps you manipulate, validate, and accurately display the date and time according to… In fact moment. js is deprecated, the development team recommends to use date-fns instead.


1 Answers

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")
like image 145
cmaurer Avatar answered Sep 30 '22 21:09

cmaurer