1

I'd like to loop through the elements of a table and change certain elements CSS if they are say 5 days old. The date column will be a string in the format Thu May 04 13:44:23 EDT 2017

I've gathered it should be something along these lines (for simplicity let's say if the date is before today) however I've played around a bit and can't get anything to go. jQueryUI library is available.

$(".t-data-grid").find('td').each (function() {
  if(Date.parse($(this).text()) < $.datepicker.formatDate('DD, d MM, yy', new Date())) {
    $(this).css('color', 'red');
  }
});     
max
  • 8,632
  • 3
  • 21
  • 55
Chris R
  • 98
  • 10
  • Also, if you're using DatePicker, this may be helpful: http://stackoverflow.com/questions/12821033/comparing-datepicker-dates-javascript – Woodrow May 15 '17 at 18:29

2 Answers2

2

Here is a pretty simple solutoin to your problem. The code is commented and should explain itself.

$(".t-data-grid").find('td').each(function() {
  // Parse the date
  var date = Date.parse($(this).text());
  // Create a date to compare against
  var fiveDaysAgo = new Date();
  // Subtract 5 days from it
  fiveDaysAgo.setDate(fiveDaysAgo.getDate()-5);
  // Compare to see if the date in the table is older than 5 days
  if(date < fiveDaysAgo) $(this).css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="t-data-grid">
  <tr>
    <td>Mon May 15 13:44:23 EDT 2017</td>
    <td>Sat May 13 13:44:23 EDT 2017</td>
    <td>Wed May 10 13:44:23 EDT 2017</td>
    <td>Mon May 08 13:44:23 EDT 2017</td>
    <td>Sun May 07 13:44:23 EDT 2017</td>
  </tr>
</table>
Jordan Soltman
  • 3,795
  • 17
  • 31
1

This line

if(Date.parse($(this).text()) < $.datepicker.formatDate('DD, d MM, yy', new Date()))

compares a Date object (which is what Date.parse() produces) to a string (which is what $.datepicker.formatDate() produces). This won't work.

Compare date objects to date objects instead.

$(".t-data-grid td").each(function () {
    var cellDate = Date.parse($(this).text());
    if (cellDate < new Date()) {
        $(this).css('color', 'red');
    }
});

Also make sure that the <td>s contain text that actually can be interpreted as a date. Not every possible date representation is recognized by Date.parse().

How you can subtract days from a JS date is clarified in this question: Subtract days from a date in JavaScript (among many others).

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628