What is the correct way to initialize Date
in EcmaScript5.
Here is what I am trying to do:
//18.02.09 12:00 - 18.02.11 24:00
var StartTime = new Date("2018-02-09T12:00:00.000Z").getTime();
var EndTime = new Date("2018-02-11T23:59:00.000Z").getTime();
What am I doing wrong here?
I am changing the time on my laptop to 18.02.09 12:01 PM. Then I am calling new Date().now()
. What I expect is to get a number which would be between StartTime
and EndTime
. But I am getting something less on two hours than StartTime
.
Strings such as "2018-02-09T12:00:00.000Z" are a standardized way to define dates, given by ISO 8601.
There are various ways to construct a Date object in JavaScript. From the Date MDN docs, we can see that one of the ways of doing that is by providing a string to be parsed. There is even an example:
var date2 = new Date("1995-12-17T03:24:00");
But you should not do that. That same page warns that creating a Date by parsing a string is not recommended since it is implementation-dependant (i.e. it might work differently depending on the browser).
Regardless, it is important to mention that in ISO 8601, ending a timestamp with the letter "Z" has a special meaning - it says that instead of considering local time, the date should be interpreted as being in UTC. So, regardless of how you decide do construct your Date object, don't forget to decide whether you want your timestamps to be localized or referring to the UTC standard time.
A safe way to construct your Date object is by providing the arguments separately:
new Date(year, month);
new Date(year, month, day);
new Date(year, month, day, hours);
new Date(year, month, day, hours, minutes);
new Date(year, month, day, hours, minutes, seconds);
new Date(year, month, day, hours, minutes, seconds, milliseconds);
You can also consider using an awesome library called MomentJS, whose size is 16.3 kB at the time of this writing (definitely worth considering), which is very famous and widely used, with over 12 million downloads per month (at the time of this writing).