I have 2 form fields in HTML namely Year and Week.Once user will select Year and week no in dropdown i want to display month Name.
Can anyone help me to get month name based on year and week no.
For ex - if i selected year as 2022 and week no as 16, then expected output is April as a month name. like wise i want dynamic function to get month name for all year and week.
Below is my code.
getMonthName() {
const year = 2022;
const week = 16;
console.log(month);
}
CodePudding user response:
Really interesting form. I came up with a solution like this;
I do not suggest you to divide per 4 weeks per month because not all months have 4 weeks. But from your input you always can now the day of year from number of week
numberOfWeek * 7 = numberOfDay
create a method :
const dateFromDay = (year, day = 1) => {
const date = new Date(year, 0);
return new Date(date.setDate(day));
}
// call the method with your inputs
const myDate = edateFromDay(2022,16*7);
// here you will have the full date
// if you want just the month than
myDate.getMonth();
CodePudding user response:
Example: https://codesandbox.io/s/damp-wood-nynj7f?file=/src/app/app.component.ts
- Create mapper for your months:
- 4 weeks = 1 month, then get input value of week covert to number and divide 4. (Example: 16 / 4 === 4)
- The result is a key of your mapper: months[divided result]
The best is a using Date libraries such as: dayjs, date-fns, moment, luxon or other.
const months = {
1: "January",
2: "February"
}
changeWeekHandler(e) {
const week = parseInt(e.target.value)
const month = Math.ceil(week / 4) // for round number to the upper (example: Math.ceil(0.25) -> 1)
this[your input field] = months[month]
}