To convert the day of the year to date, you must follow the following steps:
Date
object by calling the Date()
constructor.Date()
constructor. The first argument is the year, the second argument must be 0 for the month, and the last argument is the day of the year.Date()
constructor will return the date on that particular day of the year.let date = new Date(2022, 0, 27); console.log(date); //Thu Jan 27 2022 date = new Date(2022, 0, 100); console.log(date); //Sun Apr 10 2022 date = new Date(2022, 0, 151); console.log(date); //Tue May 31 2022
Note: JavaScript provides the Date
class for working with dates and times.
It is important to note that the Date()
constructor used in the code accepts three parameters:
Date
class follows the zero-based value of the month. So, instead of 1 for January, you have to pass 0 for January, 1 for February, and so on. Here, to convert the day of the year to date, you have to use 0; otherwise, you won't get the correct result.You might be confused as to why the value of the month parameter is 0 in the Date() constructor. The reason is that the Date class automatically changes the month as per the value of the day passed to it. For example, suppose you have passed 40 as the day, 0 as the month, and 2022 as the year to the Date() constructor.
let date = new Date(2022, 0, 40); console.log(date); //Wed Feb 09 2022
As you can see, the Date
class has changed the month from January to February because there are 31 days in January, and to represent the 40th day of the year, it has to change the month to February.