且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 gatsby graphql 中查询日期范围?

更新时间:2022-12-04 22:06:06

看起来 dateString 类型的,因此没有得到比较运算符 (gt, lt, gte, lte);真可惜,因为这真的很有用.

It looks like date is of String type, and therefore doesn't get the comparison operators (gt, lt, gte, lte); which is a shame, because this is really useful.

我认为作为一种解决方法,您可以添加一个附加字段,例如 timestamp 并将日期存储在数字中(如果您的 CMS 尚未提供).然后您可以对它们使用比较运算符.

I think as a workaround, you can add an additional field like timestamp and store the date in number (if not already provided by your CMS). Then you can use comparison operators on them.

// moment.js comes with gatsby
const moment = require('moment');

exports.onCreateNode = ({ node, actions }) => {
  const { createNodeField } = actions

  // I'm guessing your type is StrapiEvent, but it could be st else
  if (node.internal.type === `StrapiEvent`) {
    const date = node.date;

    createNodeField({
      name: 'timestamp',
      node,
      // convert date to unix timestamp & convert to number
      value: +moment(date).format('X'),
    })
  }
}

然后说您想获取从昨天开始的事件.你可以像 moment().subtract(1, 'day').format('X')//1549044285

Then say you want to get events starting from yesterday. You can get the unix timestamp like moment().subtract(1, 'day').format('X') // 1549044285

query Test {
  allStrapiEvent(filter: {
    fields: {
      timestamp: {
        gt: 1549044285
      }
    }
  }) {
    edges{
      node{
        name
        date(formatString:"MM/DD/YYYY")
      }
    }
  } 
}

不理想,但会起作用.