Fred J.
Fred J.

Reputation: 6019

Time arithmetic with moment

In This Meteor server side code for the users collections, the property createdAt shows something like this ISODate("2017-02-09T01:22:30.894Z").
And in another collection myCol I have the createdAt property with the unix timestamp in milliseconds. Moment.js is installed.
How can I check the following condition:
myCol.createdAt is after n months from the end of the month when the user was created. thx

Upvotes: 0

Views: 1096

Answers (2)

jordanwillis
jordanwillis

Reputation: 10705

Here is one approach that should work (there are of course a handful of other ways to do this...this was the first one that came to mind).

You can convert the Users createdAt property to a moment object like this (assuming your user doc is stored in a var called userOne).

var moment1 = moment(userOne.createdAt);

Then, you can convert the unix timestamp in the other collection like this (assuming the doc is stored in a var called doc).

var moment2 = moment(doc.createdAt);

Now find the end of the moment for moment1 and add in 'N' months.

moment1.endOf('month').add(N, 'months');

Finally, do your comparison.

moment2.isAfter(moment1);

Upvotes: 2

E. Sundin
E. Sundin

Reputation: 4181

I'm not sure how to get that string representation of the ISODate object, perhaps just .toString().

However, this is how you can get the time difference in months with the myCol.createdAt represented by the current date Date.now().

var isoString = "2017-02-09T01:22:30.894Z"
var today = Date.now()
console.log(moment(isoString).diff(today, 'months'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>

Upvotes: 0

Related Questions