Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Divida el mes en la primera y la segunda mitad según la fecha actual y regrese los días de la semana (JS)

tal vez alguien me puede dar algunas buenas ideas de cómo lograr esto.

Me gustaría obtener los días de la semana para las dos primeras semanas o las dos últimas semanas de un mes según la fecha actual.

Entonces, si estamos usando lo siguiente para obtener la fecha de hoy (2022-07-06)

 const current = new Date(); const date = `${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()}`;

Los resultados que estaría buscando son

 const firstHalfWeekdates = ['2022-07-04', '2022-07-05', '2022-07-06', '2022-07-07', '2022-07-08', '2022-07-11', '2022-07-12', '2022-07-13', '2022-07-14', '2022-07-15']

y si la fecha cayera en 2022-07-18 volvería

 const secondHalfWeekdates = ['2022-07-18', '2022-07-19', '2022-07-20', '2022-07-21', '2022-07-22', '2022-07-25', '2022-07-26', '2022-07-27', '2022-07-28', '2022-07-29']

También feliz de usar una biblioteca.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Tal vez esto pueda darle un comienzo. Devuelve los días de la semana, divididos por semana.

Estaba tratando de hacer todo lo que me pediste, pero me encontré con algunos problemas, por ejemplo quieres dividir el mes en 4 semanas, 2 en la primera mitad y 2 en la segunda mitad, pero por ejemplo este mes ahora julio/2022, tiene una semana que tiene solo un día de la semana (1º de julio), pero en sus resultados esperados ignoró esta semana, ¿cuál es la lógica de ignorar semanas? ¿Tiene que ser una semana completa con 5 días laborables? ¿Qué pasa con el mes pasado Jun/2022, no hubo 4 semanas completas, solo hubo 3 semanas completas, las otras 2 tienen 3 y 4 días respectivamente, qué semana ignoraría en este caso?

 function isWeekDay(day) { return day != 0 && day != 6; } function formatDateYYYYMMDD(date) { let dateString = date.toLocaleDateString('en-GB'); let year = dateString.substring(6, 10); let month = dateString.substring(3, 5); let day = dateString.substring(0, 2); return `${year}-${month}-${day}`; } function getWeekdaysOfTheCurrentMonthDividedByWeek() { let currentDate = new Date(); let month = currentDate.getMonth(); let weekdays = []; let tempDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); let week = []; while (tempDate.getMonth() == month) { if (isWeekDay(tempDate.getDay())) { week.push(formatDateYYYYMMDD(tempDate)); } else if (week.length > 0) { weekdays.push(week); week = []; } tempDate.setDate(tempDate.getDate() + 1); } return weekdays; } console.log(getWeekdaysOfTheCurrentMonthDividedByWeek());
about 4 years ago · Juan Pablo Isaza Report

0

Puede dividir el mes en semanas calendario. (por ejemplo, para julio de 2022 sería: 1-2 de julio, 3-9, 10-16, etc.)

Luego, dependiendo del día, tome la primera o la segunda mitad de las semanas.

Iterar sobre las semanas filtradas, contando los días de la semana.

Elijo incluir la tercera semana en la primera mitad del mes si hubiera 5 semanas, pero podría cambiar eso cambiando Math.ceil a Math.floor

 /** * Get the last item in an array, or undefined if the array is empty. * @template T * @param {[T]} array * @returns {T|undefined} */ const lastItem = array => array[array.length - 1]; const getWeekdays = current => { /** @type {[[Date]]} */ const weeks = []; // Get the weeks /** * Get the calendar week of the given date. * @param {Date} firstDay The first day of the week. * @returns {[Date]} */ const getWeek = firstDay => { /** @type {[Date]} */ let days = []; let dateToTest = new Date(firstDay); // Continue until the end of the week or month, whichever comes first. while ( dateToTest.getDay() <= 6 && dateToTest.getMonth() == firstDay.getMonth() ) { days.push(new Date(dateToTest)); dateToTest.setDate(dateToTest.getDate() + 1); } return days; }; // The first day of the month const firstDay = new Date(current.getFullYear(), current.getMonth()); let dateToTest = new Date(firstDay); do { weeks.push(getWeek(dateToTest)); dateToTest = new Date(lastItem(lastItem(weeks))); dateToTest.setDate(dateToTest.getDate() + 1); } while (dateToTest.getMonth() == firstDay.getMonth()); // Filter to half of the month // Get the week of the given date let currentWeek = 0; weekLoop: for (let i = 0; i < weeks.length; i++) { const week = weeks[i]; for (const day of week) { if (day == current) { currentWeek = i; break weekLoop; } } } /** @type {[[Date]]} */ let weeksInHalf = []; const numOfWeeksInFirstHalf = Math.ceil(weeks.length / 2), numOfWeeksInSecondHalf = weeks.length - numOfWeeksInFirstHalf; for ( let i = 0; i < (currentWeek < numOfWeeksInFirstHalf ? numOfWeeksInFirstHalf : numOfWeeksInSecondHalf); i++ ) { weeksInHalf.push(weeks[i]); } // Filter out weekends // Format dates return weeksInHalf .flat() .filter(day => day.getDay() > 0 && day.getDay() < 6) .map( day => `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}` ); }; // Tests for (let i = 0; i < 12; i++) { const weekdays = getWeekdays(new Date(2022, i)); weekdays.forEach(dateString => { const [year, month, day] = dateString.split("-"); const date = new Date(year, month - 1, day); if (date.getDay() == 0 || date.getDay() == 6) throw new Error("Invalid day: (day)"); else console.log(dateString) }); }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!