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

112
Views
Comparación de fechas de Javascript: tabla HTML con comparación de días atrás

Tengo una pregunta simple, pero estoy totalmente perdido. Tengo una tabla, los datos provienen de mysql con php. Tengo que comparar hoy con hace 10 días.

 <div id="employee_table"> <table class="sortable table table-bordered"> <tr> <th width="10%">date1</th> <th width="10%">date2</th> <th width="10%">date3</th> <th width="10%">date4</th> </tr> <?php while($row = mysqli_fetch_array($result)) { ?> <tr> <td><?php echo date('dm-Y', strtotime($row["date1"])) ?></td> <td><?php echo date('dm-Y', strtotime($row["date2"])) ?></td> <td><?php echo date('dm-Y', strtotime($row["date3"])) ?></td> <td><?php echo date('dm-Y', strtotime($row["date4"])) ?></td> </tr> <?php } ?> </table>

Si la fecha es inferior a 10 días, el fondo de la celda de fecha será rojo.

 <script> $(".employee_table").find('td').each(function() { // Parse the date var date = Date.parse($(this).text()); console.log(date); // Create a date to compare against var fiveDaysAgo = new Date(new Date().getTime()-(10*24*60*60*1000)); // Subtract 10 days from it var a = fiveDaysAgo.toISOString().replace(/T.*/,'').split('-').reverse().join('-') console.log(a); var result = fiveDaysAgo.getTime(); console.log(result); // Compare to see if the date in the table is older than 10 days if(result < date) $(this).css('background-color', '#CF202A'); });

Pero este código js no cambia de color correctamente. ¿Alguien ayuda? ¡Gracias!

¿Cómo puedo obtener el mismo formato de hora para la tabla y hace 10 días?

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

0

Una vez que tenga la fecha correctamente como un objeto JS Date , puede crear una instancia de una nueva fecha basada en 10 (o la cantidad de días que desee) y compararlos usando getTime() dividido por 86400000 (la cantidad de milisegundos en un solo día )

Vea si el código a continuación lo ayuda a obtener la lógica.

 let currentDate = new Date() let tenDaysAgo = changeDays(currentDate, -10) function changeDays(date, daysToChange) { var newDate = new Date(date.getTime()); newDate.setDate(date.getDate() + daysToChange); return newDate; } let daysDiff = (currentDate.getTime() - tenDaysAgo.getTime()) / 86400000 console.log(`Current Date: ${currentDate}`) console.log(`10 days ago: ${tenDaysAgo}`) console.log("Difference in days:", daysDiff) if (daysDiff <= 10) { document.getElementById("result").style.backgroundColor = "#CF202A" }
 #result { width: 200px; height: 200px; color: gray; }
 <div id="result"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Hay un pequeño problema con el selector de jQuery. Su div tiene un atributo de id , no un atributo de class .

Luego, como sus fechas se producen en formato dmY, no puede confiar en Date.parse . En su lugar, extraiga las partes de la fecha y cree una fecha a partir de ella. Puede usar esta operación para agregarle 10 días (o 5, como en su script).

Puede comparar esto con la fecha de hoy, asegurándose de que se ignore el componente de tiempo:

 // Get the date of today (midnight) once: let today = new Date(); today.setHours(0, 0, 0, 0); // Correct the selector: $("#employee_table").find('td').each(function() { // Don't parse the string. Extract the date parts let [year, month, day] = $(this).text().split("-").reverse(); // And create a date from it, adding already 5 days (day part can exceed 31) var date = new Date(+year, month-1, +day + 5); if (date < today) $(this).css('background-color', '#CF202A'); });
 <div id="employee_table"> <table class="sortable table table-bordered"> <tr> <th width="10%">date1</th> <th width="10%">date2</th> <th width="10%">date3</th> <th width="10%">date4</th> </tr> <tr> <td>01-09-2021</td> <td>4-09-2021</td> <td>8-09-2021</td> <td>12-09-2021</td> </tr> </table> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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!