0

My code

var d = new Date("2014-09-01"); 
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
days[d.getDay()]

I expects days[d.getDay()] returns Monday but It got Sunday

I am located in Pacific Time California zone

Do I miss something?

icn
  • 16,048
  • 37
  • 102
  • 135

2 Answers2

1

The string you're passing to the constructor, "2014-09-01" does not indicate a time zone. On both Chrome and Firefox (based on my tests right now), this seems to be interpreted as a GMT date. When you call getDay(), the day is given in your local time zone.

So in my case, since I am in California, the date 2014-09-01, which is midnight in GMT, is actually 5pm on August 31 in PDT.

Dan Tao
  • 122,418
  • 53
  • 286
  • 437
1

Dan Tao is right, here's how you can fix the missing timezone.

var d = new Date("2014-09-01"); 
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
d.setTime( d.getTime() + d.getTimezoneOffset()*60000 ); 

http://jsfiddle.net/s1bse8fm/2/

Related: How do you create a JavaScript Date object with a set timezone without using a string representation

Community
  • 1
  • 1
BA TabNabber
  • 1,228
  • 2
  • 13
  • 18