We become indebted to.
As the title says, if you define a variable as shown below and output it with alert,
Why is the value one month ahead output?
// current date var date1 = new Date (2020, 11, 21); // Output the current date alert (date1);
■ Output screen
November November Nov
December December Dec ← This is output
This is a rudimentary question, but I would like to ask all the experts for their advice.
■ Operating environment
・ Windows 10
・ XAMPP Ver7.4.1 (latest)
Answer # 1
For date objects, specify the month in the range 0-11.
So in this case it will be as follows, and in January it will be
0Will be specified.
var date1 = new Date (2020, 10, 21) // 2020-11-21
Answer # 2
The cause is, as kai0310 says, the month is represented by a number from 0 to 11.
The reason for such specifications is that there are quite a few cultures that do not represent the month in numbers (or rather, in English-speaking countries).
English month names are mostly derived from numbers, but since they start in March, they are out of the numbers.
In Japan, it is common to count January, February, etc., but traditionally it was called Mutsuki, Kisaragi ...
Therefore, it is common to define the month name in an array and manage its subscripts. Even when dealing with Japanese, I think it is linguistically better to do the following rather than defining something like month + 1.
month_name = ['Jan.','Feb.', ...] console.log (month_name ) //->Nov.
It may be easier to understand by the name of the day of the week that it cannot be expressed in numbers.
As in the English-speaking world, days of the week are not generally counted as 1st and 2nd in Japanese, so it is easy to understand that they are represented by numbers 0 to 6 as subscripts in the array.
By the way, in Chinese, it seems that the days of the week are counted by numbers, so it may be that we have the confusion that we have in the month of js even in the week.
Answer # 3
Regardless of the reason, if you pass it as a normal character string, Nov will be returned properly
var date1 = new Date ("2020-11-21");
By the way, the argument passed to Date is a calculated date.
new Date (2020,0,0)
You can specify like. This is one day before (0th) one day of January (0) 2020
It will be December 31, 2019