Hilal Arsa
Hilal Arsa

Reputation: 171

React js show time left from a set date to now

I've made a class component to show and render current time from new Date() function. What I wanted is to show the amount of time left by subtracting the now Date() to a time in the future. Say now is 1 p.m and the future time is 3 p.m, it will show 2:00:00.

This is my current code for current time.

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>
    );
}

Any help will be appreciated.

Upvotes: 1

Views: 10933

Answers (2)

Ishwor Timilsina
Ishwor Timilsina

Reputation: 1464

Initiate a fixed date-time of your choice. Calculate the difference (in milliseconds) between that fixed time and current time on each tick. Convert milliseconds to hours, minutes, and seconds before displaying.

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>
        );
    }
}

Upvotes: 1

Namoz
Namoz

Reputation: 540

By using Moment.js :

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

See Moment.js for further explanation.

Upvotes: 1

Related Questions