简体   繁体   English

如何从 date-fns 使用 intervalToDuration function

[英]How to use intervalToDuration function from date-fns

I tried using the intervalToDuration function from date-fns but I keep getting an error that says End Date is invalid.我尝试使用 date-fns 中的 intervalToDuration function 但我不断收到错误消息,提示结束日期无效。

My code is as follows我的代码如下

import { intervalToDuration} from "date-fns";

    remaining() {
          const now = new Date();
          const end = this.endDate;
          return intervalToDuration({
            start: now,
            end: end,
          });
        },

this.endDate is dynamically populated but for this question is equal to 2021-02-26T00:00:00.000Z this.endDate 是动态填充的,但对于这个问题等于 2021-02-26T00:00:00.000Z

Since your endDate variable is coming from an API, it is being stored as a string, not a date.由于您的endDate变量来自 API,因此它被存储为字符串,而不是日期。

Calling intervalToDuration is expecting an interval object to be passed as the parameter.调用intervalToDuration期望将间隔 object作为参数传递。 An interval consists of two Dates or Numbers (unix timestamp)间隔由两个日期或数字组成(unix 时间戳)

To correct this, you must convert endDate to a date object, below is an untested example;要更正此问题,您必须将 endDate 转换为日期 object,以下是未经测试的示例;

const remaining = () => {
  const endDate = "2021-02-26T00:00:00.000Z";
  const now = new Date();
  const end = new Date(endDate);
  return intervalToDuration({
    start: now,
    end: end
  });
};

const dur = remaining();
console.log("DURRATON ", JSON.stringify(dur));
//
// Response == DURRATON  {"years":0,"months":1,"days":8,"hours":15,"minutes":42,"seconds":0}
//

Notice: This does not handle timezones correctly.注意:这不能正确处理时区。 new Date() will create a datetime in the client timezone where it appears that your response from the API is in GMT timezone new Date()将在客户端时区创建一个日期时间,您从 API 的响应似乎在 GMT 时区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM