如何在React中从今天的日期中减去日期?

时间:2020-07-22 08:01:21

标签: javascript reactjs date math

我要显示的逻辑是:

{transfusions.map((transfusion) => {
          return (
            <tr key={transfusion.id} className="shadow-lg">
              <th scope="row">{transfusion.id}</th>
              <td>{transfusion.donor}</td>
              <td>{transfusion.blood_component}</td>
              <td>{transfusion.unit}</td>
              <td>{transfusion.created_at}</td>
              <td>
                <i
                  className="fas fa-edit"
                  onClick={() => handleUpdate(transfusion)}
                ></i>{" "}
                <i
                  className="fas fa-trash pl-1"
                  onClick={() =>
                    window.confirm(
                      "Are you sure you wish to delete this transfusion?"
                    ) && deleteTransfusion(transfusion.id)
                  }
                ></i>
              </td>
            </tr>

创建日期以这种格式2020-07-15T13:29:15.524486Z

显示

所以我想减去当前/今天的日期,就像这种格式Wed Jul 22 2020 10:57:59 GMT+0300 (East Africa Time)

最后显示这些日期之间的天数,就像整数 13

2 个答案:

答案 0 :(得分:1)

const daysBetween = new Date().getDate() - new Date('2020-07-15T13:29:15.524486Z').getDate()

答案 1 :(得分:0)

您可以使用Date构造函数:

const currentDate = new Date('Wed Jul 22 2020 10:57:59 GMT+0300 (East Africa Time)')
const oldDate = new Date('2020-07-15T13:29:15.524486Z')
currentDate - oldDate // 584923476

要显示持续时间,可以使用date-fnsluxonmomentTemporal