简体   繁体   English

比较 Mongoose Doc 中的日期和 Express 当前日期

[英]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.我正在查找提交 POST 请求的用户,然后找出他们是否在他们尝试提交的同一架构中有文档。 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.我想将当前日期与猫鼬文档中的日期进行比较,看看他们是否在过去 30 天内执行了相同的操作,如果是,则阻止他们执行所述操作。

Have tried multiple google search solutions/stackoverflow/reddit ideas, but am not getting what I want.尝试了多个谷歌搜索解决方案/stackoverflow/reddit 的想法,但没有得到我想要的。

Inside my POST request in Express在 Express 中我的 POST 请求中

 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.如果用户在我的集合中有文档的日期小于或等于上次提交后的 30 天,则阻止用户提交发布请求。

This is a simple JS date manipulation that you could use in your code.这是您可以在代码中使用的简单 JS 日期操作。

 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但是,我强烈建议使用moment.js library
Here you have the full explanation on how to use it incl.在这里你有关于如何使用它的完整解释,包括。 examples:例子:

Getting Started with Moment.js: Moment.js 入门:

Moment.js is freely available for download from the project's homepage . Moment.js可从项目主页免费下载。 Moment.js can be run from the browser as well as from within a Node.js application. Moment.js 可以在浏览器中运行,也可以在Node.js应用程序中运行。 In order to use it with Node, install the module using the following command.为了将它与 Node 一起使用,请使用以下命令安装该模块。

npm install moment Then, simply require() and use it in your application as shown below. npm install moment然后,只需 require() 并在您的应用程序中使用它,如下所示。

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,请下载脚本并使用脚本标记将其包含在内,如下例所示。 Moment.js creates a global moment object which can be used to access all the date and time parsing and manipulation functionality. Moment.js 创建一个全局时刻对象,可用于访问所有日期和时间解析和操作功能。

***Date Formatting**** ***日期格式****


In the past, I recall converting date strings into Date objects, grabbing individual pieces of data, and then performing string concatenations.过去,我记得将日期字符串转换为 Date 对象,抓取单个数据,然后执行字符串连接。 Moment.js has simplified the process of date conversion to any particular format. Moment.js简化了将日期转换为任何特定格式的过程。 Date format conversion with Moment is simple, as shown in the following example.使用 Moment 进行日期格式转换很简单,如下例所示。

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

moment() gives the current date and time, while format() converts the current date and time to the specified format. moment()给出当前日期和时间,而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. Moment.js 简化的另一个烦人的任务是日期验证。 In order to perform validation, simply pass a date string to the moment object, along with the date format, and call the isValid() method.为了执行验证,只需将日期字符串与日期格式一起传递给 moment 对象,然后调用 isValid() 方法。 This method returns true if the date is valid, and false otherwise.如果日期有效,则此方法返回 true,否则返回 false。 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() :moment()返回的对象中还有许多其他有用的标志:

overflow – This is set when an overflow occurs.溢出 - 发生溢出时设置。 An example would be the 13th month or 32nd day.例如,第 13 个月或第 32 天。

*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.例如,您可以添加或减去天、月、年等。这是通过add()subtract()方法实现的。 The following example shows how seven days, months, or weeks are added to the current date.以下示例显示了如何将 7 天、月或周添加到当前日期。

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.同样, subtract()方法如下所示。

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() .为了从当前日期计算时间, Moment.js使用名为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.”例如,以下代码显示“7 天前”。

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

dateA.fromNow();

Time From Another Date fromNow() is used to compare time to the current date.来自另一个日期的时间fromNow() 用于将时间与当前日期进行比较。 This is just a special case of from() , which compares two arbitrary dates.这只是from()一个特例,它比较两个任意日期。 An example that utilizes from() is shown below.下面显示了一个使用 from() 的示例。 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. Moment.js 提供了一种计算两个日期之间差异的方法。 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.默认情况下,差异以毫秒为单位计算,但也可以按天、月、年等返回。要计算差异,请调用 diff() 方法。 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.以下示例和演示说明了如何使用diff()

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), '毫秒'); console.log('Difference is ', dateB.diff(dateC, 'days'), 'days'); console.log('Difference is ', dateB.diff(dateC, 'days'), 'days'); console.log('Difference is ', dateB.diff(dateC, 'months'), 'months'); console.log('Difference is ', dateB.diff(dateC, 'months'), 'months');

Date Queries日期查询

Moment.js also provides date comparison methods. Moment.js还提供了日期比较方法。 These methods are isBefore() , isAfter() , and isSame() .这些方法是isBefore()isAfter()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.下面显示了一个使用 isAfter() 的示例。

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.还有一个isLeapYear()方法可以检查闰年。 I also suggest taking a look at the calendar() method, especially for your case ;)我还建议查看calendar()方法,特别是对于您的情况;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取当前日期,将字符串解析为日期并比较日期 - Get current date, parse string to date and compare the dates 将当前日期与 nodejs 中 Dynamodb 表中的现有日期进行比较 - compare current date with existing dates in Dynamodb table in nodejs 如果两个日期在当前日期之前和之后,则如何比较 - How to compare two dates if they are before and after the current date 我想比较当前日期的日期,如果日期介于日期之间,则禁用按钮 - I want to compare the dates from current date and Disable the button if the date lies between the dates 如何在 mongoose 中获取当前时间在文档中两个日期值范围内的文档? - How can I get a document in mongoose that have the current time in range of two Date values in a doc? 将时间与日期进行比较 - Compare time with date in express 如何在当前日期/特定日期中添加分钟,并在JavaScript中比较两个日期? - How to add min to current date/specific date and compare both dates in javascript? mongoose和express.js中的日期冲突 - Conflicting dates in mongoose and express.js 比较硬编码日期和当前日期 - Compare hardcoded date with the current date 如何在JS中比较两个日期? 一个是用户选择的,一个是当前日期 - How to compare two dates in JS? One is user selected and one is the current date
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM