0

I have managed to automatically build an HTML table based on a output from my ERP system, and managed to use CSS to format it easily. The last step is conditional formatting in a Date Field. If the date is < from now make the field RED if it's between 4 <> 7 days from NOW make it YELLOW else "no formatting.

I have gotten this far on dozens of examples from this site, and I am hoping you can help me do some basic DATE MATH which for some reason I just can't get my head around.

Right now my date field is in the td:nth-child(4) and I want to compaire it to the current date.

    <script>

    $(document).ready(function() {

            $('table td:nth-child(4)').each(function() {
                var D1 = $(this).text();
                var D2 = new Date();

                if ((D1 - D2) < 4) {
                    $(this).css('backgroundColor', 'RED'); 
                }
                else if((D1 - D2) < 7) && ((D1 - D2) > 4) {
                    $(this).css('backgroundColor', 'YELLOW'); 
                }
                else {
                    $(this).css('backgroundColor', '#99faa0'); 
                }

            });
            event.preventDefault();
    });

    </script>
  • This might help http://stackoverflow.com/questions/41948/how-do-i-get-the-difference-between-two-dates-in-javascript – Coleman Jun 01 '16 at 20:01

1 Answers1

0

You need to convert and compare the dates properly. Below is the example to compare dates.

Reference:

Get difference between 2 dates in javascript?

var _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

Working sample

https://jsfiddle.net/zsLfh3kj/1/

Community
  • 1
  • 1
Thangaraja
  • 926
  • 6
  • 20