Reputation: 191
Today is 07 May 2016, Saturday But when I implement a js practice, the getDay() always return the correct number plus one. So I did this test.
Today is Saturday, so I expect to return 5 rather than 6.
Upvotes: 0
Views: 3174
Reputation: 1
you can simply add 6 and use modulus operator.
var d = new Date(2016, 5, 20);
var weekday = (d.getDay() + 6) % 7;
Upvotes: 0
Reputation: 5256
The day of the week:
var d = new Date(2016, 5, 20); // June 20, 2016
d.getDay();
Starting the count from 0 (Sunday), 1 means Monday and etc...
@Mike C:
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
You will have the same situation with month too. The value returned by getMonth() is an integer between 0 and 11. 0 corresponds to January, 1 to February, and so on.
0 January
1 February
2 March
3 April
4 May
5 June
6 July
7 August
8 September
9 October
10 November
11 December
var d = new Date(2016, 5, 20); // June 20, 2016
d.getMonth(); // 5
Why?
As assumed @ChristopherW this can help to reference in an array of names.
var
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(2016, 5, 20); // June 20, 2016
months[d.getMonth()]; // "June"
days[d.getDay()]; // "Monday"
It is very convenient for developers. But there is another reason for zero-indexing. The syntax of JavaScript is actually derived from C. Lets analize C's localtime function.
The C library function struct tm *localtime(const time_t *timer) uses the time pointed by timer to fill a tm structure with the values that represent the corresponding local time. The value of timer is broken up into the structure tm and expressed in the local time zone.
struct tm *localtime(const time_t *timer)
This function returns a pointer to a tm structure with the time information filled in. Following is the tm structure information:
struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ };
As you see month starts from 0 to 11, day of the week from 0 to 6.
Upvotes: 0
Reputation: 32511
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So if Sunday is 0 then you get these values for the other days:
Upvotes: 3