在秒表中创建“ saveTime”功能。从结束日期减去开始日期,包括暂停

时间:2019-07-18 11:13:34

标签: javascript reactjs

创建时间记录功能时遇到问题。单击start给我开始日期'dateStart'。点击“保存”可给我结束日期'dateEnd' -> (this.state.dateStart + (Date.now () - this.state.timerStart))})dateEnd如何将日期转换为ISOString格式?从dateEnd中减去'dateStart'可以得到秒表传递的数字。我还必须包括停止按钮。

所有代码:https://stackblitz.com/edit/react-f7kkgo

图片:https://imgur.com/R5hajk0

startTimer = () => {
    this.setState({
      timerOn: true,
      timerTime: this.state.timerTime,
      timerStart: Date.now() - this.state.timerTime,
      dateStart: (Date.now() - this.state.timerTime).toISOString();
    });
    this.timer = setInterval(() => {
      this.setState({
        timerTime: Date.now() - this.state.timerStart
      });
    }, 10);
  };

  stopTimer = () => {
    this.setState({ timerOn: false });
    clearInterval(this.timer);
  };

  resetTimer = () => {
    this.setState({
      timerStart: 0,
      timerTime: 0
    });
  };

  saveTimer = () => {
    this.setState({
      timerOn: false,
      dateEnd:  (this.state.dateStart + (Date.now() - 
                this.state.timerStart)).toISOString()
    }) 

    this.resetTimer();
    clearInterval(this.timer);
   }

1 个答案:

答案 0 :(得分:1)

您必须在Date.toISOString()实例上使用Date,而不是在实例方法(即Date.now())上使用。我已经在CodeSandbox.

中更新了文件
  saveTimer = () => {
    let eve=(this.state.dateStart + (this.state.dateStart  - 
                this.state.timerStart));
    let date_new=new Date(eve);
    this.setState({
      timerOn: false,
      dateEnd: date_new.toISOString()
  }) 
  console.log(this.state.dateEnd);

  this.resetTimer();
  clearInterval(this.timer);
  }