Jonathan Wood
Jonathan Wood

Reputation: 67175

JavaScript Changes My Date Based on Browser Time Zone

I am trying to create a Date object in JavaScript, passing a string like this:

2014-11-30T00:00:00.0000000

However, the value of the Date object is:

Sat Nov 29 2014 17:00:00 GMT-0700 (Mountain Standard Time)

It changed it to 11/29 when I want 11/30. Is there any way I can make the date 2014-11-30, regardless of what time zone the browser is in?

Note: One possible workaround is to use the Date(year, month, day) constructor; however, I am constructing the data in a JSON string, which doesn't appear to support this.

EDIT:

Actually, I just did a test and created a date using Date(2015, 1, 1) and it gives me:

Mon Feb 02 2015 00:00:00 GMT-0700 (Mountain Standard Time)

So I can't even create a date that way and have it be the date I want. I don't understand why this is so difficult.

Upvotes: 0

Views: 931

Answers (1)

Madbreaks
Madbreaks

Reputation: 19529

You can use Date.UTC

The UTC() method differs from the Date constructor in two ways.

  • Date.UTC() uses universal time instead of the local time.
  • Date.UTC() returns a time value as a number instead of creating a Date object.

EDIT - why does SO insist on making links so hard to spot? That, up there, is a link to the docs in case that wasn't obvious.

EDIT 2 - I think I misunderstood. Try this:

var d = new Date('2014-11-30T00:00:00.0000000'); 
var utc = new Date(
              d.getUTCFullYear(),
              d.getUTCMonth(),
              d.getUTCDate(),
              d.getUTCHours(),
              d.getUTCMinutes(),
              d.getUTCSeconds()
           );
alert('d: ' + d + "\n" + 'utc: ' + utc);

Upvotes: 1

Related Questions