Issue
I have 2 form fields in HTML namely Year and Week.
Once the user selects a Year and a week from the dropdowns, I want to display the month Name for the selected year and week.
Can anyone help me to get month name based on year and iso week numbers.
For example: If I selected year as 2022 and week no as 16, then the expected output is April as a month name.
This shoud be a function that returns the month name for a given year and week.
Below is my sampke code.
getMonthName() {
const year = 2022;
const week = 16;
console.log(month);
}
Solution
The following will display the month name (short form) for the given ISO week number and year.
function getMonthName(week, year) {
let d =new Date(year,0,1+(week-1)*7);
d.getUTCDay()<5?d.setUTCDate(d.getUTCDate()-d.getUTCDay()+1):d.setUTCDate(d.getUTCDate()+8-d.getUTCDay());
return (""+d).split(" ")[1];
}
console.log(getMonthName(1,2022));
console.log(getMonthName(11,2022));
console.log(getMonthName(16,2022));
Answered By - Mohsen Alyafei
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.