3

To start off, I know that the day of week in javascript starts at 0, Sunday = 0, Saturday = 6.

However, there is something simple that I am missing here, but the following code always returns what I want, but 1 less.

This should return 6, but returns 5.

var string = "2014-06-21";
var temp = new Date(string);
alert(temp.getDay());

Anybody have any ideas whats going wrong, and how it may be fixed? Thanks.

Bobby W
  • 836
  • 8
  • 22

2 Answers2

4

If you create a date from a string be sure to specify the time:

var string = "2014-06-21 00:00:00";
var temp = new Date(string);
alert(temp.getDay());

You are probably getting the previous day because you are not specifying the time (in the date string). In this case, your current time zone will be used (mine is GMT-03h)

Another option is to create a date using the Date constructor which takes numbers as it's parameters:

new Date(year,month,day);

Or, in your case:

var temp = new Date(2014, 6, 21);
alert(temp.getDay());
Marlon Bernardes
  • 13,265
  • 7
  • 37
  • 44
0

If you don't specify a time in your string it will default to your current time zone.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

jonespm
  • 382
  • 2
  • 17