Reputation: 2432
Code:
const date = new Date(2020, 05, 10)
const options = {
year: 'numeric',
month: 'long',
day: 'numeric'
}
const formattedDate = date.toLocaleDateString('en', options);
console.log(formattedDate);
Why the output is June 10, 2020? I went through documentation but did not understand. Could somebody help me understand what's happening in above code.
Upvotes: 3
Views: 843
Reputation: 3714
Here options = { year: 'numeric', month: 'long', day: 'numeric'}
month is config as month: long
so it will show June
, short
will show Jun
, but if you pass numeric
for a month in options
it will output interestingly month as 6
, and Since month starts from 0-11 and since you passed 5 as a month in Date constructor, so it will output June as a month.
Upvotes: 1
Reputation: 20431
This has more to do with the Date()
constructor.
There are multiple formats to pass date into the constructor. When using Individual date and time component values format, the second parameter is monthIndex. That is why 5 - corresponds to June, and for May you will have to use 4.
From the docs:
Integer value representing the month, beginning with 0 for January to 11 for December. If a value greater than 11 is passed in, then those months will be added to the date; for example, new Date(1990, 12, 1) will return January 1st, 1991
As you can see this has nothing to do with your options. The month is June even before that.
const date = new Date(2020, 05, 10)
console.log(date);
const formattedDate = date.toLocaleDateString('en', options);
console.log(formattedDate);
Note: You might be seeing a different day, depending but that is because the date returned initially is platform-independent. So it shows based on GMT.
Upvotes: 1