首页 > 解决方案 > 节点 - 尝试查找和过滤落入今天时间线的对象数组(时间戳)

问题描述

我有一个 CSV 文件,我将其转换为对象数组。所有事件(行)都有一个开始和结束的时间戳。我正在尝试搜索今天的所有事件。我正在查看 moment.js 来执行此操作,但是在搜索时遇到错误。

数据看起来像这样。注意:数据集较旧,因此我试图欺骗 2019 年 8 月 5 日的“今天”变量,该变量在当天的事件范围内

{
            "T_START": "1565019000",
            "T_END": "1565023500",
            "PROJECT": "Billionaire",

        },
        {
            "T_START": "1565024400",
            "T_END": "1565028000",
            "PROJECT": "John's Place",

        },
        {
            "T_START": "1565024400",
            "T_END": "1565029800",
            "PROJECT": "The Smith Show",

        }

到目前为止,这是我的代码。有了这个,我得到一个空数组,但有 200 个成功案例


router.get('/', async (req, res) => {
    try {
        // Get schedules from CSV File
        let schedules = await csv().fromFile(getCsv('scheduallworkorders.csv'));

        // Check for query strings
        if (req.query.search == 'today') {
            // Get todays schedules

            // Get date
            let today = moment('08-05-2019', 'MM-DD-YYYY');

            // Filter for today
            let todaysSchedules = schedules.filter(value => {
                return moment(value.T_START).isBetween(
                    today,
                    today,
                    null,
                    '[]'
                );
                //return value.T_START == today;
            });

            return res.status(200).json({
                message: 'Success getting todays schedules',
                schedules: todaysSchedules
            });
        }

        // Default - Get all schedules
        res.status(200).json({
            message: 'Success getting all schedules',
            schedules: schedules
        });
    } catch (error) {
        res.status(500).json({
            message: 'Error getting all schedules',
            error: error
        });
    }
});

标签: node.jsdatetimemomentjs

解决方案


这应该可以解决问题

let todaysSchedules = schedules.filter(value => {
  return moment(parseInt(value.T_START)*1000).isSame(today,"day")
})

编辑

或者如果您希望今天的日期在 T_START 和 T_END 之间,也可以这样

let todaysSchedules = schedules.filter(value => {
  return today.isBetween(
    parseInt(value.T_START)*1000,
    parseInt(value.T_END)*1000,
    "day",
    "[]"
  )
});

推荐阅读