Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
Rajshri Mohan K S Avatar asked Aug 23 '16 17:08

Rajshri Mohan K S


People also ask

How do you add time to a Date object?

To add 2 hours to the Date Object first, we get the current time by using the Date. getTime() method and then add 2 hour's milliseconds value (2 * 60 * 60 * 1000) to it and pass the added value to the Date Object.

How do you create a Date object?

You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.


1 Answers

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.

like image 189
T.J. Crowder Avatar answered Sep 29 '22 06:09

T.J. Crowder