0

I'm rendering local JSON to the browser and each item contains a modified date in ISO 8601 time (such as "2019-03-19T18:50:39Z"). The plan is to make it so that if the Created date is older than 30 days then it will be hidden from the div.

Should I convert the time into a more readable format (such as 03/19/2019)? Would it be easier to work with?

New JSON data could be added at any point, which is why I need to have my code be dynamic. It's part of the reason why I'm struggling with this one.

JS snippet:

import testjson from './test.json';

export default class {
    constructor() { 
    }

    loadNewCourses() {
        let newCrs = testjson.d.results
            .sort(function(a, b) { // sorts by newest
                return (a.Created < b.Created) ? 1 : ((b.Created < a.Created) ? -1 : 0)
            })
            .filter((el, idx, self) => { // no duplicates
                return (idx === self.map(el => el.Category).indexOf(el.Category))
            })
            .map(x => {
                return {
                    "Category": x.Category,
                    "Title": x.Title,
                    "Description": x.Description,
                    "Created": x.Created
                }
            })



$.each(newCrs, function(idx, val) { // ---- does this look right?
        let current = new Date();
        let expiry = new Date(val.Created)

        if (current.getTime() > expiry.getTime()) {
            $('.categoryName').hide();
        } else if (current.getTime() < expiry.getTime()) {
            $('.categoryName').show();
        }
    })

        let curIndex = 0;
        $.each(newCrs, function(idx, val) {
            curIndex++; // this line must be here
            let targetDiv = $("div.new-training-div > div[col='" + curIndex + "']");

            let modalTrigger = $('<div />', {
                'class': 'categoryName',
                'data-category': val.Category,
                'data-target': '#modal-id',
                'data-toggle': 'modal',
                'text': val.Category
            });

            modalTrigger.prepend("<span class='triangle-right'>&blacktriangleright;</span>");

            targetDiv.append(modalTrigger);

            if(curIndex == 4) {
                curIndex = 0;
            }

        })

    } // ------------------ loadNewCourses

}

JSON snippet:

},
        "FileSystemObjectType": 0,
        "Id": 80,
        "Title": "Rome",
        "Category": "WorldCapitals",
        "Description": "A capital city (or simply capital) is the municipality exercising primary status in a country, state, province, or other administrative region, usually as its seat of government.",
        "TopTrainingCourse": false,
        "VideoLink": "https:\/\/www.google.com",
        "ID": 80,
        "Modified": "2019-03-19T18:50:39Z",
        "Created": "2019-03-19T18:50:39Z"

      }
...etc
Bodrov
  • 840
  • 1
  • 15
  • 29
  • `Date.now() - new Date("2019-03-19T18:50:39Z").getTime()` will get you the number of milliseconds between now and that date. If that amount of milliseconds is over 30 days, don't show it – Taplar Mar 20 '19 at 17:44
  • Granted it looks like the isotime doesn't have a timezone, on it, so the first time you subtract from should probably be the UTC time – Taplar Mar 20 '19 at 17:45
  • "*Should I convert the time into a more readable format*": only if you want humans to read it. A format like MM/DD/YYYY is ambiguous to the vast majority of people who use some other format. – RobG Mar 20 '19 at 21:48

1 Answers1

0

I often say «When it comes to dates... Look for moment.js! It handles everything so easilly...»

I did not attempt to re-create your code exactly... But I took your json sample to make a demo where there are 3 courses on Rome, Paris and England. And only England was created more than 30 days ago (as of today march 20th!).

Notice that line: expiry.add(30,"days") where 30 days are added to the json "Created" date.

Can't be simplier...

var newCrs = [
  {
    "FileSystemObjectType": 0,
    "Id": 80,
    "Title": "Rome",
    "Category": "WorldCapitals",
    "Description": "A capital city (or simply capital) is the municipality exercising primary status in a country, state, province, or other administrative region, usually as its seat of government.",
    "TopTrainingCourse": false,
    "VideoLink": "https:\/\/www.google.com",
    "ID": 80,
    "Modified": "2019-03-19T18:50:39Z",
    "Created": "2019-03-19T18:50:39Z"  // Yesterday, march 19th
  },
  {
    "FileSystemObjectType": 0,
    "Id": 81,
    "Title": "Paris",
    "Category": "WorldCapitals",
    "Description": "A capital city (or simply capital) is the municipality exercising primary status in a country, state, province, or other administrative region, usually as its seat of government.",
    "TopTrainingCourse": false,
    "VideoLink": "https:\/\/www.google.com",
    "ID": 81,
    "Modified": "2019-03-19T18:50:39Z",
    "Created": "2019-03-01T18:00:00Z" // march 1st
  },
  {
    "FileSystemObjectType": 0,
    "Id": 82,
    "Title": "England",
    "Category": "WorldCapitals",
    "Description": "A capital city (or simply capital) is the municipality exercising primary status in a country, state, province, or other administrative region, usually as its seat of government.",
    "TopTrainingCourse": false,
    "VideoLink": "https:\/\/www.google.com",
    "ID": 82,
    "Modified": "2019-03-19T18:50:39Z",
    "Created": "2019-01-01T18:00:00Z" // february 1st
  }
];


$.each(newCrs, function(idx, val) {
  let current = moment();
  let expiry = moment(val.Created)

  if (current > expiry.add(30,"days")) {
    console.log( val.Title +" is hidden." );
  } else {
    console.log( val.Title +" is shown." );
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • Libraries are useful, but to use something as large as moment.js just to get the [*difference between two dates in days*](https://stackoverflow.com/search?q=%5Bjavascript%5D+difference+between+dates) seems excessive. – RobG Mar 20 '19 at 21:45
  • @RobG: Moment.js is 16.8KB... – Louys Patrice Bessette Mar 20 '19 at 22:54
  • 1
    Which is quite a bit larger than `dateA.setDate(dateA.getDate() + 30) < dateB`. :-) – RobG Mar 21 '19 at 10:29