简体   繁体   中英

Compare Dates In Mongoose Doc and Express Current Date

I am finding the user that is submitting the POST request, and then finding out if they have a document in the same Schema they are trying to submit. If they have multiple, I sort and return the most recent one. I'd like to compare the current date to the date found in the mongoose document to see if they have done the same action in the last 30 days, and if so prevent them from doing said action.

Have tried multiple google search solutions/stackoverflow/reddit ideas, but am not getting what I want.

Inside my POST request in Express

 let currentDate = new Date(); console.log(currentDate); User.findOne({ user: req.user.id }) .then(user => { Scores.find().sort({date: -1}).limit(1) .select('date') .then(date => { if (currentDate - date <= 30) { res.json({toosoon: 'You are attempting to do this action too many times in one month'}) }) }) })

Prevent the user from being able to submit the post request if they have a document in my collection that has a date that is less than or equal to the 30 days from last submission.

This is a simple JS date manipulation that you could use in your code.

 let date = new Date(); console.log('Today is: ' + date.toLocaleString()); date.setDate(date.getDate() - 30); console.log('30 days ago was: ' + date.toLocaleString());

However, I strongly suggest using the moment.js library
Here you have the full explanation on how to use it incl. examples:

Getting Started with Moment.js:

Moment.js is freely available for download from the project's homepage . Moment.js can be run from the browser as well as from within a Node.js application. In order to use it with Node, install the module using the following command.

npm install moment Then, simply require() and use it in your application as shown below.

const moment = require('moment');

moment().format();

In order to run Moment from the browser, download the script and include it using a script tag, as shown in the following example. Moment.js creates a global moment object which can be used to access all the date and time parsing and manipulation functionality.

***Date Formatting****


In the past, I recall converting date strings into Date objects, grabbing individual pieces of data, and then performing string concatenations. Moment.js has simplified the process of date conversion to any particular format. Date format conversion with Moment is simple, as shown in the following example.

moment().format('YYYY MM DD');

moment() gives the current date and time, while format() converts the current date and time to the specified format. This example formats a date as a four digit year, followed by a space, followed by a two digit month, another space, and a two digit date. You can see this code in action by checking out this demo.

Date Validation


Another annoying task that Moment.js has simplified is date validation. In order to perform validation, simply pass a date string to the moment object, along with the date format, and call the isValid() method. This method returns true if the date is valid, and false otherwise. An example of this is shown below, along with this accompanying demo.

let dateEntered = $('#txtEnteredDate').val();

if (!moment(dateEntered,'MM-DD-YYYY').isValid()) {
  console.log('Invalid Date');
} else {
  console.log('Valid Date');
}

There are a number of other helpful flags in the object returned by moment() :

overflow – This is set when an overflow occurs. An example would be the 13th month or 32nd day.

*invalidMonth* – Set when the month is invalid, like Jannnuaarry.
*empty* – Set when the entered date contains nothing parsable.
*nullInput* – Set when the entered date is null.

Manipulating Dates


There are a number of options for manipulating the moment object. For example, you can add or subtract days, months, years, etc. This is achieved via the add() and subtract() methods. The following example shows how seven days, months, or weeks are added to the current date.

moment().add('days', 7);    // adds 7 days to current date
moment().add('months', 7);  // adds 7 months to current date
moment().add('years', 7);   // adds 7 years to current date

Similarly, the subtract() method is shown below.

moment().subtract('days', 7);   // subtracts 7 days to current date
moment().subtract('months', 7); // subtracts 7 months to current date
moment().subtract('years', 7);  // subtracts 7 years to current date

Time From Now


Another common task is determining how much time exists between two dates. For calculating time from the current date, Moment.js uses a method named fromNow() . Here is a sample which checks how much time exists from the current time:

moment().fromNow();

This code sample displays “a few seconds ago.” If we supply date to the moment object it would display the time range from now as per the difference. For example, the following code displays “7 days ago.”

const dateA = moment().subtract('days', 7);

dateA.fromNow();

Time From Another Date fromNow() is used to compare time to the current date. This is just a special case of from() , which compares two arbitrary dates. An example that utilizes from() is shown below. This code displays “in a day.” You can see this code in action by checking out this demo.

const dateB = moment('2019-12-12');
const dateC = moment('2019-12-11');
console.log(dateB.from(dateC));

Calculating the Difference Between Dates


Moment.js offers a way to calculate the difference between two dates. The difference is calculated in milliseconds by default , but can also be returned in days, months, years, etc. To compute the difference, call the diff() method. This method takes a date as its first argument. The unit of time can be specified using the optional second argument. If this is not included, then milliseconds are used. The following example and demo illustrate how diff() is used.

const dateB = moment('2019-11-11');
const dateC = moment('2019-10-11');

console.log('Difference is ', dateB.diff(dateC), 'milliseconds'); console.log('Difference is ', dateB.diff(dateC, 'days'), 'days'); console.log('Difference is ', dateB.diff(dateC, 'months'), 'months');

Date Queries

Moment.js also provides date comparison methods. These methods are isBefore() , isAfter() , and isSame() . As the names imply, these methods return a Boolean indicating if one date is before, after, or equal to another date. An example that uses isAfter() is shown below.

console.log(moment('2010-09-20').isAfter('2010-10-19')); // returns false
console.log(moment('2010-11-20').isAfter('2010-10-19')); // returns true

There is also an isLeapYear() method that checks for leap years. I also suggest taking a look at the calendar() method, especially for your case ;)

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