I'm trying to create a Date in NodeJS with zero time i.e. something like 2016-08-23T00:00:00.000Z
. I tried the following code:
var dateOnly = new Date(2016, 7, 23, 0, 0, 0, 0);
console.log(dateOnly);
While I expected the output to be as mentioned above, I got this:
2016-08-22T18:30:00.000Z
How do I create a Date object like I wanted?
I'm trying to create a Date in NodeJS with zero time i.e. something like 2016-08-23T00:00:00.000Z
. I tried the following code:
var dateOnly = new Date(2016, 7, 23, 0, 0, 0, 0);
console.log(dateOnly);
While I expected the output to be as mentioned above, I got this:
2016-08-22T18:30:00.000Z
How do I create a Date object like I wanted?
Share Improve this question asked Aug 23, 2016 at 17:11 Rajshri Mohan K SRajshri Mohan K S 1,76920 silver badges33 bronze badges3 Answers
Reset to default 10The key thing about JavaScript's Date
type is that it gives you two different views of the same information: One in local time, and the other in UTC (loosely, GMT).
What's going on in your code is that new Date
interprets its arguments as local time (in your timezone), but then the console displayed it in UTC (the Z
suffix tells us that). Your timezone is apparently GMT+05:30, which is why the UTC version is five and a half hours earlier than the date/time you specified to new Date
.
If you'd output that date as a string in your local timezone (e.g., from toString
, or using getHours
and such), you would have gotten all zeros for hours, minutes, seconds, and milliseconds. It's the same information (the date is the same point in time), just two different views of it.
So the key thing is to make sure you stick with just the one view of the date, both on input and output. So you can either:
Create it like you did and output it using the local timezone functions (
toString
,getHours
, etc.), orCreated it via
Date.UTC
so it interprets your arguments in UTC, and then use UTC/GMT methods when displaying it such astoISOString
,getUTCHours
, etc.:var dateOnlyInUTC = new Date(Date.UTC(2016, 7, 23)); console.log(dateOnlyInUTC.toISOString()); // "2016-08-23T00:00:00.000Z"
Side note: The hours, minutes, seconds, and milliseconds arguments of both new Date
and Date.UTC
default to 0, you don't need to specify them if you want zeroes there.
Maybe this can Help:
let startDate = new Date();
let correctedStartDate = new Date(Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()));
Source:
2024-02-09T17:25:29.000Z
Result :
2024-02-09T00:00:00.000Z
You could always just initialize the Date object with your desired date, then use the Date objects .setHours()
method to set it to midnight.
See also: What is the best way to initialize a JavaScript Date to midnight?