如何在流星JS中获得今天和过去7天的记录?

时间:2015-04-16 08:27:21

标签: mongodb meteor mongodb-query

如何获取Meteor JS中的今天和过去7天的记录。我正在使用创建日期

var date = new Date();

我正在使用MongoDB集合代码,如下所示:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

var start = new Date(""+yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z");
var end = new Date(""+yyyy+"-"+mm+"-"+(dd+1)+"T00:00:00.000Z");

var fetchResult = Profile.find({created:{$gte: start, $lt: end}});

怎么办?

2 个答案:

答案 0 :(得分:3)

尝试从当前日期的时间戳中减去天数:

var today = new Date();
var weekAgoDate = new Date();
weekAgoDate.setUTCDate(weekAgoDate.getDate() - 7);

var fetchResult = Profile.find({created:{$gte: weekAgoDate, $lt: today}});

使用 momentjs API非常直观且易于理解:

var today = moment();
var weekAgoDate = today.subtract("days", 7); // same as today.add("days", -7)

var fetchResult = Profile.find({created:{$gte: weekAgoDate.toDate(), $lt: today.toDate()}});

注意:要获取Moment.js包装的原生Date对象,请使用 toDate()

答案 1 :(得分:0)

请查看以下摘录

var today_date = new Date(frame_date());
var range_date = new Date(today_date);

range_date.setDate(today_date.getDate() - 1);    // for toady records
Profile.find({ 'created': {$gte: range_date, $lte: today_date}})  


range_date.setDate(today_date.getDate() - 7);   // for last 7 days  records
Profile.find({ 'created': {$gte: range_date, $lte: today_date}})  

此处函数frame_date定义 -

function frame_date() {
    var time = require('time');
    var timestamp = new time.Date();
//        var timestamp = new Date();
    timestamp.setTimezone("Australia/Sydney");  //you can set timezone here
    var getYear = timestamp.getFullYear();
    var getMnth = timestamp.getMonth();
    var getDate = timestamp.getDate();
    var gethours = timestamp.getHours();
    var getMins = timestamp.getMinutes();
    var getSecs = timestamp.getSeconds();
    var getMilisecs = timestamp.getMilliseconds();
    if (getDate < 10) {
        getDate = "0" + getDate;
    }
    if (getMnth < 9) {
        getMnth = parseInt(getMnth) + 1
        getMnth = "0" + getMnth;
    } else {
        getMnth = getMnth + 1;
    }
    if (gethours < 10) {
        gethours = "0" + gethours;
    }
    if (getMins < 10) {
        getMins = "0" + getMins;
    }
    if (getSecs < 10) {
        getSecs = "0" + getSecs;
    }
    var getMiliSecs = getMilisecs;
    if (getMilisecs < 10) {
        getMiliSecs = "0" + getMilisecs;
    } else if (getMilisecs < 100) {
        getMiliSecs = "00" + getMilisecs;
    } else {
        getMiliSecs = getMilisecs;
    }


    var final_framed_date = getYear + "-" + getMnth + "-" + getDate + " " + gethours + ":" + getMins + ":" + getSecs + "." + getMiliSecs;
    return final_framed_date;

}

感谢