1

I'm trying to set my Date object in javascript, but I keep getting wrong date. This is how I set

var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var day = today.getDate();
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();

var create_date = new Date(year,month,day,0,0,0).toISOString();

My local datetime is 2015-11-17 21:00:00, however this creates 2015-11-16 22:00:00.000Z. If I use hour, minute and second variables in date constructor it creates the correct time in mongodb. I want to set date as 2015-11-17 00:00:00. What might be the problem?

Thank you

EDIT

Even the date is set correct in javascript, date in mongo db is seen as 2015-11-16 22:00:00.000Z

1 Answer 1

3

To set the date to the start of today, use the setHours() method of the Date object as follows:

var create_date = new Date();
create_date.setHours(0,0,0,0);
console.log(create_date); // prints Tue Nov 17 2015 00:00:00 GMT+0000 (GMT Standard Time)

For UTC, use setUTCHours():

create_date.setUTCHours(0,0,0,0);
Sign up to request clarification or add additional context in comments.

2 Comments

My document's date in mongodb is seen as 2015-11-16 22:00:00.000Z. However, console print is true. Why can't I just enter the same date into mongodb?
Try create_date.setUTCHours(0,0,0,0);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.