Milan Nosáľ
Milan Nosáľ

Reputation: 19737

A bug in creating a new Date object from day/month/year JavaScript?

A quite simple question. I have three numbers, a year, a month and a day.

var year = parseInt($("#date_year").val());
var month = parseInt($("#date_month").val()) - 1; // to start from 0
var day = parseInt($("#date_day").val());

I want a proper Date object in JS initialized with these values. I tried this:

var date = new Date(year, month, day);

However, it is behaving weirdly, a day is not correct and also the time is not 00:00:00, e.g. for values:

year: 1987
month: 9
day: 28

after printing date.toUTCString() I get:

Tue, 27 Oct 1987 23:00:00 GMT

when I would expect:

Wed, 28 Oct 1987 00:00:00 GMT

Can anyone please point out, what I am not understanding correctly?

Upvotes: 1

Views: 1280

Answers (4)

jerielmari
jerielmari

Reputation: 171

The parameters of the Date object gets the run time time-zone, which is then converted and stored as the number of milliseconds after Jan 1 1970 UTC.

So this:

var date = new Date(1987, 9, 28);

  • Let's say above is ran with the time-zone offset of +0800 (Manila)
  • It becomes "Oct 28 1987 00:00:00 GMT+0800"
  • It is converted to UTC by subtracting the offset,
  • which is then stored as 562348800000 or "1987-10-27T16:00:00.000Z"

This was done because websites are accessed all over the world, and it would make it easier to let the browser take care of displaying the time according to the local time-zone it is in and just store objects in a common reference frame, which in this case is UTC.

You can use:

date.toString()

This will show the Date object in an American English representation of the date in the run time time-zone. Or:

date.toLocaleString()

You can indicate the locale and even the time-zone that you want to display it in. Check compatibility

Upvotes: 1

chris97ong
chris97ong

Reputation: 7060

Use date.toString() instead of date.toUTCString().

date.toString() returns "Wed Oct 28 1987 00:00:00 GMT+0800 (Malay Peninsula Standard Time)"

If you need it to return "Wed, 28 Oct 1987 00:00:00 GMT", you can try this:

var date = new Date(year, month, day);
dateString = date.toString();
dateString = dateString.split("+")[0];
dateString = dateString.replace(" ", ", "); // replace first space with comma + space

This makes dateString = "Wed, Oct 28 1987 00:00:00 GMT"

Upvotes: 1

Stefan Dimov
Stefan Dimov

Reputation: 591

Using this:

date.toString();

The toUTCString() method converts a date to a string, using the UTC time zone.

The toString() method returns a string representing the specified Date object (doesn't convert the date).

Upvotes: 1

Nikhil Batra
Nikhil Batra

Reputation: 3148

This is due to difference in timeZones.

toUTCString(): Convert a Date object to a string, according to universal time.

Upvotes: 1

Related Questions