直接贴代码
import React, { Component } from "react";
class Index extends Component {
constructor(props) {
super(props);
this.state = {
day: 0,
hour: 0,
minute: 0,
second: 0,
};
}
componentDidMount() {
let startDate = Date.parse(this.props.start.replace(/-/g, "/"));
let endDate = Date.parse(this.props.end.replace(/-/g, "/"));
this.countFun(startDate, endDate);
}
componentWillUnmount() {
clearInterval(this.timer);
}
countFun = (start, end) => {
let now_time = Date.parse(new Date());
let remaining = 0;
if (now_time > start && now_time < end) {
remaining = end - now_time;
} else {
remaining = 0;
}
this.timer = setInterval(() => {
if (remaining > 1000) {
remaining -= 1000;
let day = Math.floor(remaining / 1000 / 3600 / 24);
let hour = Math.floor((remaining / 1000 / 3600) % 24);
let minute = Math.floor((remaining / 1000 / 60) % 60);
let second = Math.floor((remaining / 1000) % 60);
this.setState({
day: day,
hour: hour < 10 ? "0" + hour : hour,
minute: minute < 10 ? "0" + minute : minute,
second: second < 10 ? "0" + second : second,
});
} else {
clearInterval(this.timer);
}
}, 1000);
};
render() {
return (
<div>
{this.state.day}天{this.state.hour}:{this.state.minute}:
{this.state.second}
</div>
);
}
}
export default Index;