简体   繁体   中英

Add, subtract and compare date and time on Meteor Mongo

I am running a collection on Meteor Mongo that has a field called last_activity and another one called expire_date .

In this particular case I need to get items from that collection whose last_activity was N hours ago.

In a second case I have to save an expire_date that is N months from creation time (right now).

How can I add or subtract date or time on Mongo/Meteor (if they use different methods I would be glad if someone explained both briefly) and make comparisons with them?

Plus, which one is the best idea to choose when we are getting something from the database? Will I save some processing time if I do it directly on Mongo?

You can use Moment.js to add or subtract time in readable English. There's a Meteor package to install Moment easily.

$ meteor add momentjs:moment

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


moment().add(Number, String);
moment().add(Duration);
moment().add(Object);

// For example, add 7 days from now:
moment().add(7, 'days');

After you generate the right date object you can persist it on your Mongo database.

It depends on how do you store your date. You have at least two options.

Date.now()
1437215759517

or

new Date()
Date 2015-07-18T10:36:04.981Z

In first case it is amount of ms from some special point of time in linux(unix) world :D And you can easily add any time to existing one. For example:

1 week
7 * 1 days
7 * 24 hours
7 * 24 * 60 minutes
7 * 24 * 60 * 60 seconds
7 * 24 * 60 * 60 * 1000 ms

So in your code you will have something like this (1 week from now):

expire_date = Date.now() + 7 * (24 * 60 * 60 * 1000)

And yes. To display this date in eye-pleasing format I would suggest moment.js

Date.now()
1437216383841

moment(Date.now()).format('LL')
"July 18, 2015"

moment(Date.now() + 7 * (24 * 60 * 60 * 1000)).fromNow()
"in 7 days"

Store all date|time in ISO - {createdAt: ISODate("2015-08-12T09:36:42Z"). Use momentjs:

moment().toDate()
var currentDateInISO = moment().toDate()
posts.insert({createdAt: currentDateInISO});

Compare 2 ISODate:

var t1 = moment().toDate()
var t2 = moment().toDate()
moment(t1).isBefore(t2) // True

http://momentjs.com/docs/#/query/is-before/

Have fun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM