React js显示从设置日期到现在的剩余时间

时间:2018-06-20 20:25:58

标签: reactjs datetime components

我已经制作了一个类组件,以通过新的Date()函数显示和呈现当前时间。我想要的是通过将现在的Date()减去将来的时间来显示剩余的时间。假设现在是下午1点,将来的时间是下午3点,它将显示2:00:00。

这是我当前时间的当前代码。

class Clock extends React.Component {
constructor(props) {
    super(props);
    this.state = { date: new Date() };
}
componentDidMount() {
    this.timerID = setInterval(
        () => this.tick(),
        1000
    );
}
componentWillUnmount() {
    clearInterval(this.timerID);
}
tick() {
    this.setState({
        date: new Date()
    });
}

render() {
    return (
        <div>
            <h2>Waktu tersisa {this.state.date.toLocaleTimeString()}.</h2>
        </div>
    );
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

通过使用Moment.js

const currentDate = moment();
const future = moment('2019-03-02 10:03:02');
const timeLeft = moment(future.diff(currentDate)).format("HH:mm:ss");

有关更多说明,请参见Moment.js

答案 1 :(得分:0)

启动您选择的固定日期时间。计算每个刻度上的固定时间和当前时间之间的时差(以毫秒为单位)。在显示之前将毫秒转换为小时,分钟和秒。

class Clock extends React.Component {
    constructor(props) {
        super(props);
        let fixDate = (new Date()).setHours(15,0,0); // for 3:00:00 pm
        let currDate = new Date();
        this.state = { fixDate, diff: fixDate-currDate };
    }

    ....

    tick() {
        this.setState((prevState, props) => ({
            diff: prevState.fixDate - (new Date()).getTime(),
        }));
    }

    ....

    render() {
        const { diff } = this.state;
        const hours = Math.floor(diff/(60*60*1000));
        const mins = Math.floor((diff-(hours*60*60*1000))/(60*1000));
        const secs = Math.floor((diff-(hours*60*60*1000)-(mins*60*1000))/1000);

        return (
            <div>
                <h2>Waktu tersisa {hours}:{mins}:{secs}</h2>
            </div>
        );
    }
}