简体   繁体   English

从当前日期查找上一年

[英]Find the previous year from current date

I need in javascript to pass the query in mongodb for record deletion我需要在 javascript 中传递 mongodb 中的查询以删除记录

My date in the db is in this format: "12 Feb 2019 06:45:34 GMT" and I have to get the dates 1 year before for record deletion.我在数据库中的日期采用以下格式:“2019 年 2 月 12 日 06:45:34 GMT”,我必须获取 1 年前的日期才能删除记录。 How i can do it.我该怎么做。

 var d = new Date(); var gmt = d.toUTCString(); var s = gmt.slice(5); var ne = s.setFullYear(s.getFullYear() - 1); console.log(ne)

You can simply parse it using new Date("12 Feb 2019 06:45:34 GMT") and then use the setFullYear like you did.您可以简单地使用new Date("12 Feb 2019 06:45:34 GMT")解析它,然后像您一样使用setFullYear

 var strDate = "12 Feb 2019 06:45:34 GMT" var d = new Date(strDate); d.setFullYear(d.getFullYear() - 1); console.log(d.toString())

var dateString = "12 Feb 2019 06:45:34 GMT";
var d = new Date(dateString);

var s = new Date(d);
s.setFullYear(s.getFullYear() - 1);

console.log(s);

Create some data set创建一些数据集

> var dateString = "12 Feb 2019 06:45:34 GMT";
> var dateObject = new Date(dateString);

> db.datetest1.insert({createdDateTime: dateObject})
WriteResult({ "nInserted" : 1 })
// One more record
> db.datetest1.find()
{ "_id" : ObjectId("5def0a895645c25f96ce22ba"), "createdDateTime" : ISODate("2019-02-12T06:45:34Z") }
> var dateString = "12 Feb 2017 06:45:34 GMT";
> var dateObject = new Date(dateString);
> db.datetest1.insert({createdDateTime: dateObject})
WriteResult({ "nInserted" : 1 })

Find the inserted data into MongoDB collection查找插入的数据到 MongoDB 集合中

> db.datetest1.find()
{ "_id" : ObjectId("5def0a895645c25f96ce22ba"), "createdDateTime" : ISODate("2019-02-12T06:45:34Z") }
{ "_id" : ObjectId("5def0abc5645c25f96ce22bb"), "createdDateTime" : ISODate("2017-02-12T06:45:34Z") }

Now Wanted to delete one year older data from collection现在想从集合中删除一年前的数据

> var currentDate = new Date() // current date
> currentDate.setFullYear(currentDate.getFullYear() -1) // subtract one year
1544410990689
> currentDate
ISODate("2018-12-10T03:03:10.689Z")
// Remove with $multi : true for more than one records
> db.datetest1.remove({createdDateTime: {$lte: currentDate}}, {$multi:true})
WriteResult({ "nRemoved" : 1 })
// Left data in the collection
> db.datetest1.find()
{ "_id" : ObjectId("5def0a895645c25f96ce22ba"), "createdDateTime" : ISODate("2019-02-12T06:45:34Z") }
> 

So, answer to your question is that just create current date object and subtract one year as currentDate.setFullYear(currentDate.getFullYear() -1) and then pass that value into the MongoDB remove query as the above.因此,您的问题的答案是,只需创建当前日期对象并减去一年作为currentDate.setFullYear(currentDate.getFullYear() -1)然后将该值传递到MongoDB remove查询中,如上所述。

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

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