【问题标题】:Convert Unix Timestamp + add 1 hour转换 Unix 时间戳 + 加 1 小时
【发布时间】:2018-03-23 17:53:04
【问题描述】:

我正在使用 map reactjs 对多行进行倒计时

我为多行倒计时 1 小时。它工作正常,但我不知道如何实时执行此操作,例如使用 new Date()

我有 Unix 日期,例如 1521827247 我如何转换它并添加 1 小时,这样我就可以倒计时了

这是我的代码

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: {},
      seconds: 3600,
      unix: 1521827247
    };
    this.timer = 0;
    this.startTimer = this.startTimer.bind(this);
    this.countDown = this.countDown.bind(this);
  }

  secondsToTime(secs) {
    let hours = Math.floor(secs / (60 * 60));
    let divisor_for_minutes = secs % (60 * 60);
    let minutes = Math.floor(divisor_for_minutes / 60);
    let divisor_for_seconds = divisor_for_minutes % 60;
    let seconds = Math.ceil(divisor_for_seconds);

    let obj = {
      "h": hours,
      "m": minutes,
      "s": seconds
    };
    return obj;
  }

  componentDidMount() {
    let timeLeftVar = this.secondsToTime(this.state.seconds);
    this.setState({ time: timeLeftVar });
    this.startTimer()
  }

  startTimer() {
    if (this.timer == 0) {
      this.timer = setInterval(this.countDown, 1000);
    }
  }

  countDown() {
    // Remove one second, set state so a re-render happens.
    let seconds = this.state.seconds - 1;
    this.setState({
      time: this.secondsToTime(seconds),
      seconds: seconds,
    });

    // Check if we're at zero.
    if (seconds == 0) {
      clearInterval(this.timer);
    }
  }

  render() {
    return (
      <div>
        car {this.props.data.car} <b>Finish:</b>h: {this.state.time.h}  m: {this.state.time.m} s: {this.state.time.s}
      </div>
        );
  }
}
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: [{ "id": 1, "car": 'Audi 2018' }] };
  }

  addCar = () => {
    this.setState(prevState => ({
      data: [...prevState.data, { "id": 2, "car": 'New Car' }]
    }))
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.data.map(row => <MyComponent data={row} key={row.id} />)}
        </ul>
        <button onClick={this.addCar}>Add Car</button>
      </div>
    );
  }
}


ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

我可以做什么或者有没有可以使用的 npm 包?

【问题讨论】:

标签: javascript reactjs unix-timestamp


【解决方案1】:

我看到您正在通过秒数进行倒计时,截至您的代码已通过 3600(以秒为单位的 1 小时)。将 3600 添加到实时 unix 纪元应该会给您以秒为单位的正确时间,您可以将其传递以生成您想要开始倒计时的正确时间。

在您的代码中: this.state = { time: {}, seconds: 3600, unix: 1521827247 };

尝试: seconds: current_unix_time + 3600

这是另一个来源: Javascript: how to add n minutes to unix timestamp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2023-03-18
    • 2020-10-19
    相关资源
    最近更新 更多