【问题标题】:Hiding JSON element if date value is older than 30 days [duplicate]如果日期值早于 30 天,则隐藏 JSON 元素 [重复]
【发布时间】:2019-03-20 17:42:19
【问题描述】:

我正在向浏览器呈现本地 JSON,并且每个项目都包含 ISO 8601 时间的修改日期(例如“2019-03-19T18:50:39Z”)。计划是这样,如果创建日期超过 30 天,那么它将在 div 中隐藏。

我应该将时间转换为更易读的格式(例如 03/19/2019)吗?会更容易合作吗?

可以随时添加新的 JSON 数据,这就是为什么我需要让我的代码是动态的。这也是我为此苦苦挣扎的部分原因。

JS sn-p:

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 sn-p:

},
        "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

【问题讨论】:

  • Date.now() - new Date("2019-03-19T18:50:39Z").getTime() 将为您提供从现在到该日期之间的毫秒数。如果该毫秒数超过 30 天,请不要显示
  • 当然,isotime 似乎没有时区,所以第一次减去可能应该是 UTC 时间
  • "我应该将时间转换成更易读的格式":仅当您希望人类阅读时。对于使用其他格式的绝大多数人来说,像 MM/DD/YYYY 这样的格式是模棱两可的。

标签: javascript jquery json date datetime


【解决方案1】:

我经常说«谈到约会...寻找moment.js!它可以轻松处理所有事情...»

我并没有尝试完全重新创建您的代码...但是我使用您的 json 示例制作了一个演示,其中在 Rome、Paris 上有 3 门课程英格兰。并且只有 英格兰 是在 30 多天前创建的(截至今天 3 月 20 日!)。

注意这一行:expiry.add(30,"days"),其中 30 天被添加到 json“创建”日期。

再简单不过了……

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>

【讨论】:

  • 库是有用的,但是为了得到difference between two dates in days而使用像moment.js这样大的东西似乎太过分了。
  • @RobG: Moment.js 是 16.8KB...
  • 这比dateA.setDate(dateA.getDate() + 30) &lt; dateB 大很多。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 2017-08-24
  • 2017-05-20
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
相关资源
最近更新 更多