Search code examples
javascriptnode.jsdate

Create a Date object with zero time in NodeJS


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?


Solution

  • The 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:

    1. Create it like you did and output it using the local timezone functions (toString, getHours, etc.), or

    2. Created it via Date.UTC so it interprets your arguments in UTC, and then use UTC/GMT methods when displaying it such as toISOString, 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.