1

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?

0

4 Answers 4

1

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"

Sign up to request clarification or add additional context in comments.

Comments

1

This is due to difference in timeZones.

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

Comments

1

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).

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.