-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClock.js
More file actions
49 lines (41 loc) · 1.03 KB
/
Clock.js
File metadata and controls
49 lines (41 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React, { Component } from 'react'
export default class Clock extends Component {
constructor(props) {
super(props);
this.state = this.getTime();
}
componentDidMount() {
this.setTimer();
}
componentWillUnmount() {
if (this.timeout) {
clearTimeout(this.timeout);
}
}
setTimer() {
clearTimeout(this.timeout);
this.timeout = setTimeout(this.updateClock.bind(this), 1000);
}
updateClock() {
this.setState(this.getTime, this.setTimer);
}
getTime() {
const currentTime = new Date();
return {
hours: currentTime.getHours(),
minutes: currentTime.getMinutes(),
seconds: currentTime.getSeconds(),
ampm: currentTime.getHours() >= 12 ? 'pm' : 'am'
}
}
render() {
const {hours, minutes, seconds, ampm} = this.state;
return (
<div className="clock">
{hours == 0 ? 12 : hours > 12 ? hours - 12 : hours}:
{minutes > 9 ? minutes : `0${minutes}`}:
{seconds > 9 ? seconds : `0${seconds}`} {ampm}
</div>
);
}
}