You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React多行倒计时:Unix时间戳转换加1小时实现实时倒计时

Real-Time Countdown with Unix Timestamp + 1 Hour in React

Got it, let's adjust your code to make the countdown real-time based on your Unix timestamp plus an hour. Here's a step-by-step breakdown and modified implementation:

Core Concepts We'll Use

  • Convert your Unix timestamp (seconds) to a target end time by adding 3600 seconds (1 hour)
  • Calculate remaining time dynamically using the current time (instead of just decrementing a fixed number) to avoid timer drift and keep it accurate
  • Make the component reusable for multi-row scenarios by tying each countdown to its own timestamp prop

Modified Component Code

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    // Calculate end time: passed Unix timestamp + 1 hour (3600 seconds)
    const endTime = props.data.unix + 3600;
    this.state = {
      time: {},
      endTime: endTime
    };
    this.timer = 0;
    this.startTimer = this.startTimer.bind(this);
    this.countDown = this.countDown.bind(this);
    this.secondsToTime = this.secondsToTime.bind(this);
  }

  // Helper to convert seconds to hours/minutes/seconds object
  secondsToTime(secs) {
    if (secs <= 0) return { h: 0, m: 0, s: 0 };
    
    const hours = Math.floor(secs / (60 * 60));
    const divisorForMinutes = secs % (60 * 60);
    const minutes = Math.floor(divisorForMinutes / 60);
    const seconds = Math.floor(divisorForMinutes % 60);
    
    return { h: hours, m: minutes, s: seconds };
  }

  componentDidMount() {
    // Initialize the countdown display
    this.countDown();
    this.startTimer();
  }

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

  countDown() {
    // Get current time in Unix seconds (convert ms to s)
    const currentTime = Math.floor(new Date().getTime() / 1000);
    // Calculate remaining seconds until end time
    const remainingSeconds = this.state.endTime - currentTime;

    if (remainingSeconds <= 0) {
      // Stop timer when countdown finishes
      clearInterval(this.timer);
      this.setState({ time: this.secondsToTime(0) });
    } else {
      this.setState({ time: this.secondsToTime(remainingSeconds) });
    }
  }

  render() {
    const { h, m, s } = this.state.time;
    return (
      <div>
        Car {this.props.data.car} 
        <b>Finish:</b> {h}h : {m}m : {s}s
      </div>
    );
  }
}

// Example usage for multi-row countdowns
// const carData = [
//   { car: "Sedan", unix: 1521827247 },
//   { car: "SUV", unix: 1521830847 },
//   { car: "Truck", unix: 1521834447 }
// ];
// {carData.map(car => <MyComponent key={car.car} data={car} />)}

Key Changes Explained

  • Dynamic End Time: Each component instance calculates its own end time using the unix timestamp from props + 3600 seconds. This works perfectly for multi-row scenarios where each item needs its own countdown.
  • Real-Time Accuracy: Instead of subtracting 1 second every interval, we calculate the difference between the current time and the target end time each second. This eliminates timer drift and ensures the countdown stays in sync with actual time.
  • Edge Case Handling: Added logic to stop the timer and display 00:00:00 once the countdown finishes.
  • Helper Function Tweaks: Fixed the secondsToTime function to handle 0 seconds properly and use Math.floor for seconds (prevents showing 60 seconds instead of 0).

内容的提问来源于stack exchange,提问作者Laura delgado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:58:25