Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
Javascript Date Compare - HTML Table with compare days ago

I have a simple question But im totally lost. I have a table, data comes from mysql with php. I have to compare today with 10 days ago.

                   <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('d-m-Y', strtotime($row["date1"])) ?></td> 
                                <td><?php echo date('d-m-Y', strtotime($row["date2"])) ?></td> 
                                <td><?php echo date('d-m-Y', strtotime($row["date3"])) ?></td> 
                                <td><?php echo date('d-m-Y', strtotime($row["date4"])) ?></td>                                        
                           </tr>  
                           <?php  
                           }  
                           ?>  
                      </table>  

If date less than 10 days date cell background will be red.

<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');
        });

But this js code not change color correctly. Anyone help ? Thank you!

how can i get same time format for table and 10 days ago?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Once you have the date correctly as a JS Date object, you can just instantiate a new date based on 10 (or the amount of days you want) and compare them using getTime() divided by 86400000 (the amount of milliseconds in a single day)

See if below code helps you to get the logic.

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 Relatório

0

There is a little issue with the jQuery selector. Your div has an id attribute, not a class attribute.

Then, as your dates are produced in d-m-Y format, you cannot rely on Date.parse. Instead extract the date parts and create a date from it. You can use this operation to already add 10 days to it (or 5, like in your script).

You can compare this to the date of today, making sure the time component is ignored:

// 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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda