2015-04-16 88 views
1

如何獲得記錄今天和流星JS.I過去的7天記錄我使用創建日期如何獲得今天和過去7天記錄流星JS?

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}}); 

怎麼辦?

+0

http://stackoverflow.com/questions/563406/add-days-to- datetime只是從新的日期()刪除7天,比較,它應該沒事 – Sindis

回答

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()

+0

沒有得到,我在這個集合字段集合中使用創建的字段賦予新的日期()在DB集合商店這樣的「創建」:ISODate 「2015年-04-16T08:54:06.543Z「)。 @chridam – user2344293

+0

Ur發佈的回答不工作weekAgoDate來了NaN.Can你檢查一次。@ chridam – user2344293

+0

@ user2344293我已經更新了答案,你可以試試讓我知道這種改變是怎麼回事? – chridam

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; 

} 

感謝

相關問題