Quiero escribir un script en Js que indique la cantidad de días en un mes y el caso de prueba debe satisfacer lo siguiente:
Introduzca un mes: enero. salida-> enero tiene 31 dias.
Introduce un mes: Salida ENERO-> Enero tiene 31 dias
Introduce un mes: salida febrero-> febrero tiene 28 días.
Introduce un mes: Salida FEbruero->Febrero tiene 28 dias.
y mi código es:
let a = prompt('Enter the month:'); let b = a.charAt(0).toUpperCase(); let c = a.slice(1, a.length).toLowerCase(); let Month = (b + c); if ('January' === Month || 'March' === Month || 'May' === Month || 'July' === Month || 'Agust' === Month || 'October' === Month || 'December' === Month) { console.log(`${Month} has 31 days`) } else if ('February' === Month) { console.log(`${Month} has 28 days`); } else if ('April' === Month || 'June' === Month || 'September' === Month || 'November' === Month) { console.log(`${Month} has 30 days`) } else{ console.log('Re-Enter'); }Satisface solo el primer caso de prueba. Si alguien me ayuda con la lógica correcta que satisface todos los casos de prueba.
Puede calcular recuperar el número de días de un mes en cualquier año recuperando el valor de fecha de una Date para el próximo mes con un valor de fecha de 0 . Aquí hay una pequeña fábrica para determinar los números de día por mes (numéricos o usando el nombre de un mes):
const getNDaysForMonthFactory = _ => { const months = (`january,february,march,april,may,june,`+ `july,august,september,october,november,december`).split(','); const byNr = (year, month) => new Date(year, month, 0).getDate(); return { byNr, byName: (year, month) => { const m = months.findIndex( m => m === month.toLowerCase()); return m > -1 ? byNr(year, m + 1) : `[${month}] is not a valid month`; }, }; } const {byNr, byName} = getNDaysForMonthFactory(); console.log(`(byNr) 6 2022: ${byNr(2022, 6)} days`); console.log(`(byNr) 2 2022: ${byNr(2022, 2)} days`); console.log(`(byNr) 2 2000: ${byNr(2000, 2)} days`); console.log(`(byName) february 2000: ${byName(2000, `FEBRuary`)} days`); console.log(`(byName) nothing 2022: ${byName(2022, `nothing`)}`); // so showDays(); document.addEventListener(`change`, handle); document.addEventListener(`keyup`, handle); function showDays() { const [month, year] = [ +document.querySelector(`#month`).value, +document.querySelector(`#year`).value ]; document.querySelector(`#nDays`).textContent = `${byNr(year, month)} days`; } function handle(evt) { if (evt.target.id === `year` || evt.target.id === `month`) { return showDays(); } } <select id="month"> <option value="1" selected>January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <input id="year" type="number" value="2022"> <span id="nDays"></span>Esta es una versión modificada de la respuesta de @KooiInc sin el bucle while
const getNDays = (year, month) => { let daysOfMonth = 0; let date = new Date(Date.UTC(year, month, 1, 0, 0, 0)); date.setDate(date.getDate() - 1); return date.getDate(); } console.log(`june 2022: ${getNDays(2022, 6)} days`); console.log(`february 2022: ${getNDays(2022, 2)} days`); console.log(`february 2000: ${getNDays(2000, 2)} days`); console.log(`february 1900: ${getNDays(1900, 2)} days`); // so showDays(); document.addEventListener(`change`, handle); function showDays() { const [month, year] = [ +document.querySelector(`#month`).value, +document.querySelector(`#year`).value ]; document.querySelector(`#nDays`).textContent = `${getNDays(year, month)} days`; } function handle(evt) { if (evt.target.id === `year` || evt.target.id === `month`) { return showDays(); } } <select id="month"> <option value="1" selected>January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <input id="year" type="number" value="2022"> <span id="nDays"></span>Podemos crear una función formatDaysInMonth() que tomará un nombre de mes como enero, FEBRERO, etc. y un año y devolverá el mes y los días formateados, como "Febrero de 2020 tiene 29 días":
function monthNameToMonth(monthName) { const months = { january: 1, february: 2, march: 3, april: 4, may: 5, june: 6, july: 7, august: 8, september: 9, october: 10, november: 11, december: 12 }; return months[monthName.toLowerCase()] } function getDaysInMonth(year, month) { return new Date(year, month, 0).getDate(); } function formatDaysInMonth(year, monthName) { let month = monthNameToMonth(monthName); let days = getDaysInMonth(year, month); monthName = monthName.toUpperCase().slice(0,1) + monthName.toLowerCase().slice(1); return `${monthName} ${year} has ${days} days`; } let monthName = prompt('Enter the month name:'); let year = prompt('Enter the year:'); console.log(formatDaysInMonth(year, monthName)) .as-console-wrapper { max-height: 100% !important; }