Question

I have seen a few posts about this, but none that I have learnt from.

I need to send a certain date-timestamp to REST API, and it needs to look like this:

2014-01-17 00:00:00.000

So I need two, one for the current months first day, and the current months last day, so something like this:

2014-02-01 00:00:00.000

2014-02-28 00:00:00.000

I have used the following code:

var date = new Date(),
    y = date.getFullYear(),
    m = date.getMonth(),
    firstDay = new Date(y, m, 1),
    lastDay = new Date(y, m + 1, 0),
    querydate = '"_createdAt" : {"$gt" : "' +
        y + '-' + m + '-' + firstDay + ' 00:00:00.000" , "$lt" : "' +
        y + '-' + m + '-' + lastDay + ' 00:00:00.000"}';

But this is the output I get, via dev mode on the browser:

"_createdAt" : {"$gt" : "2014-1-Sat Feb 01 2014 00:00:00 GMT+0000 (GMT) 00:00:00.000" , "$lt" : "2014-1-Fri Feb 28 2014 00:00:00 GMT+0000 (GMT) 00:00:00.000"}}

As you can see, its giving me the correct year, but the month needs to be two digits, and for the last and first day, its giving the full date.

Any ideas how I could manage this ?

Was it helpful?

Solution

See the similarity to the other posts now?

Javascript

function padLeft(arg) {
    if (arg < 10) {
        arg = '0' + arg;
    }

    return arg;
}

function myFormat(dateObject) {
    return [
        dateObject.getFullYear(),
        padLeft(dateObject.getMonth() + 1),
        padLeft(dateObject.getDate())
    ].join('-') + ' 00:00:00.000';
}

var date = new Date(),
    y = date.getFullYear(),
    m = date.getMonth(),
    firstDay = new Date(y, m, 1),
    lastDay = new Date(y, m + 1, 0),
    querydate = '"_createdAt" : {"$gt" : "' +
        myFormat(firstDay) + ' , "$lt" : "' +
        myFormat(lastDay) + '"}';

console.log(querydate);

Output

"_createdAt" : {"$gt" : "2014-02-01 00:00:00.000 , "$lt" : "2014-02-28 00:00:00.000"} 

On jsFiddle

OTHER TIPS

Moment.js

For datetime things in javascript I prefer to use moment.js; a small library for nice datetime displaying and calculating.

What you are trying to do would look like this:

moment("2014-05-15 22:15:01").format("YYYY-MM-DD HH:mm:ss") // "2014-05-15, 22:15:01"
var date = new Date(), 
y = date.getFullYear(),
m = date.getMonth()  
var firstDay = new Date(y, m, 1).getDate() ;
var lastDay = new Date(y, m + 1, 0).getDate()
var querydate = '"_createdAt" : {"$gt" : "'+y+'-'+m+'-'+firstDay+' 00:00:00.000" , "$lt" : "'+y+'-'+m+'-'+lastDay+' 00:00:00.000"}';    
    var getTimeStamp = function() {
    var tStamp;
    var cd = new Date();
     if ( (cd.getMonth() + 1) < 10 )
        var tStamp = ( cd.getFullYear() + "-0" + (cd.getMonth() + 1) + "-" + cd.getDate() + " 00:00:00.000");
    else
        var tStamp = ( cd.getFullYear() + "-" + (cd.getMonth() + 1) + "-" + cd.getDate() + " 00:00:00.000");
    return tStamp;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top