【问题标题】:comparsion and match the dates比较和匹配日期
【发布时间】:2020-05-10 21:07:27
【问题描述】:

我遇到了关于 javascript 日期的问题。我想比较start date and end date JSON 数据并显示在特定插槽newprevious, newcurrent, newfirstdate and newseconddate

反应组件

我试过了,但我的情况不行

        <div class="row">
          {this.state.data && this.state.data.length
            ? // this.state.data[index].start_date.toString() > this.state.newprevious
              // this.state.data[index].start_date.toString() > this.state.newcurrent
              // this.state.data[index].start_date.toString() > this.state.newfirstdate
              // this.state.data[index].start_date.toString() > this.state.newseconddate
              this.state.data.map(
                ({ cust_full_name, full_name, start_date }, index) => (
                  <div class="row" key={index}>
                    slot: {index + 1}
                    <p>{start_date}</p>
                    <p>{cust_full_name}</p>
                  </div>

我的工作演示:

https://codesandbox.io/s/priceless-bird-ue3iu?file=/src/App.js

我的代码输出:

只需匹配 start date and end date JSON 数据并显示在特定的 previous , current , first and second date 插槽中

预期输出:

我该怎么办?请帮帮我?

【问题讨论】:

  • 小心建议将字符串转换为日期的答案。 “2020-05-11 01:45:50”不是 ECMA-262 支持的格式,因此解析取决于实现,至少一个当前浏览器会将其解析为无效日期。见Why does Date.parse give incorrect results?

标签: javascript reactjs date datetime match


【解决方案1】:

假设

this.state.data 中的日期格式正确。

解决方案

您可以在 JavaScript 中比较两个日期,只需将它们包含在 Date() 中即可。

var date1, date2;
date1 = new Date("put ur date here to compare");
date2 = new Date("Dec 15, 2014 21:20:15" ); 
if (date1 > date2) {
 alert("Date1 is the recent date.");
 } 
else { 
alert("Date 2 is the recent date."); 
}

【讨论】:

    【解决方案2】:

    您可以使用Array.filter 删除所有未通过检查的项目并仅呈现那些通过检查的项目。

    另外,如果您想比较日期,您应该执行以下操作:

    const prev = "2020-05-11 01:45:50";
    const second = "2020-05-11 03:15:50";
    
    // read why it needs to be normalized
    // https://stackoverflow.com/a/45152231
    const normalize = (value) => {
      return value.replace(/ /g, "T") + "Z"
    }
    
    // excluding `min` and `max`
    const isBetween = (date) => {
      const min = new Date(normalize(prev))
      const max = new Date(normalize(second))
      const dateToCompare = new Date(normalize(date))
      
      return min < dateToCompare && dateToCompare < max;
    }
    
    console.log("2020-05-11 01:00:00", isBetween("2020-05-11 01:00:00"));
    console.log("2020-05-11 02:45:00", isBetween("2020-05-11 02:45:00"));

    您可以这样做:

    class App extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          newprevious: ["2020-05-11 01:45:50"],
          newseconddate: ["2020-05-11 03:15:50"],
    
          data: [
            {
              id: "1",
              start_date: "2020-05-11 03:45:00",
              end_date: "2020-05-11 04:00:00",
              cust_full_name: "furqan"
            },
            {
              id: "2",
              start_date: "2020-05-11 02:45:00",
              end_date: "2020-05-11 03:00:00",
              cust_full_name: "ahmed"
            },
            {
              id: "3",
              start_date: "2020-05-11 02:30:00",
              end_date: "2020-05-11 02:45:00",
              cust_full_name: "ali"
            },
            {
              id: "3",
              start_date: "2020-05-11 01:00:00",
              end_date: "2020-05-11 01:15:00",
              cust_full_name: "mubeem"
            }
          ]
        };
      }
    
      render() {
        const { data, newprevious, newseconddate } = this.state;
        const filtered =
          data && data.length
            ? data.filter(({ start_date }) => {
                // normalize b/c `Safari` doesn't recognize this format as a proper date
                // see: https://stackoverflow.com/a/45152231
                const normalize = val => val.replace(/ /g, "T") + "Z";
    
                const min = new Date(normalize(newprevious[0]));
                const max = new Date(normalize(newseconddate[0]));
                const itemDate = new Date(normalize(start_date));
    
                return min < itemDate && itemDate < max;
              })
            : [];
        return (
          <div className="App">
            <div className="row">
              <p>{this.state.newprevious}</p>
              <p>{this.state.newseconddate}</p>
              <hr />
              {filtered.map(({ cust_full_name, start_date }, index) => (
                <div className="row" key={index}>
                  slot: {index + 1}
                  <p>{start_date}</p>
                  <p>{cust_full_name}</p>
                </div>
              ))}
            </div>
          </div>
        );
      }
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById("app")
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="app"></div>

    这是一个如何根据 OP 的编辑在不同时间段中对项目进行分组的示例:

    const data = [
      {
        id: "1",
        start_date: "2020-05-11 03:45:00",
        end_date: "2020-05-11 04:00:00",
        cust_full_name: "furqan"
      },
      {
        id: "2",
        start_date: "2020-05-11 02:45:00",
        end_date: "2020-05-11 03:00:00",
        cust_full_name: "ahmed"
      },
      {
        id: "3",
        start_date: "2020-05-11 02:30:00",
        end_date: "2020-05-11 02:45:00",
        cust_full_name: "ali"
      },
      {
        id: "3",
        start_date: "2020-05-11 01:00:00",
        end_date: "2020-05-11 01:15:00",
        cust_full_name: "mubeem"
      }
    ];
    
    const prev = "2020-05-11 01:45:50";
    const curr = "2020-05-11 02:15:50";
    const first = "2020-05-11 02:45:50";
    const second = "2020-05-11 03:15:50";
    const dates = [prev, curr, first, second];
    
    const result = dates.reduce((accumulator, date, idx, collection) => {
      if (idx === collection.length - 1) {
        return accumulator;
      }
      const min = new Date(normalize(date));
      const max = new Date(normalize(collection[idx + 1]));
      const foundItemWithDateBetween = findItemWithDateBetween(min, max, data);
    
      if (!foundItemWithDateBetween) {
        return accumulator;
      }
      return {
        ...accumulator,
        [idx]: {
          min: date,
          max: collection[idx + 1],
          item: foundItemWithDateBetween
        }
      };
    }, {});
    
    console.log("result", result);
    
    function normalize(value) {
      return value.replace(/ /g, "T") + "Z";
    }
    function findItemWithDateBetween(min, max, items) {
      return items.find(({ start_date, end_date }) => {
        const startDate = new Date(normalize(start_date));
        const endDate = new Date(normalize(end_date));
        return min < startDate && endDate < max;
      });
    }

    【讨论】:

    • 好的,我试试你的代码@
    • 谢谢我再问一件事? @
    • @MHasan 是的,当然
    • 我应该如何比较 previous , current , first and second datestart and end date@
    • 我已经更新了sandbox code,你可以查看@
    【解决方案3】:

    我已经使用 JS 库中的 new Date() 适应了您的解决方案。您可以查看solution

    【讨论】:

    • 好的,我试试你的代码@
    • 谢谢我再问一件事? @
    • 答案应该解释为什么 OP 有问题以及您的代码如何修复它。你应该在这里发布代码,而不是其他地方。
    • 这是一个反应代码,我想展示最终结果的样子。我提出了一个解决方案。 OP 没有问题,他不知道如何继续。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2016-08-25
    相关资源
    最近更新 更多