Skip to content

Instantly share code, notes, and snippets.

@clc80
Created May 23, 2018 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clc80/68f8fd43ccae44112e4c6edcf81c99ae to your computer and use it in GitHub Desktop.
Save clc80/68f8fd43ccae44112e4c6edcf81c99ae to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
class Clock extends React.Component {
constructor(props) {
super(props);
const currentTime = new Date()
this.state = {
hours: currentTime.getHours(),
minutes: currentTime.getMinutes(),
seconds: currentTime.getSeconds(),
ampm: currentTime.getHours() >= 12 ? 'pm': 'am'
};
this.setTimer();
}
setTimer() {
//will run for 1 second and then call updateClock
setTimeout(this.updateClock.bind(this), 1000);
}
updateClock() {
//After one second it will update the Clock by one second
const currentTime = new Date();
this.setState({
hours: currentTime.getHours(),
minutes: currentTime.getMinutes(),
seconds: currentTime.getSeconds(),
ampm: currentTime.getHours() >= 12 ? 'pm' : 'am'
}, this.setTimer());
}
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 > 0 ? seconds: `0${seconds}`
}
{ampm}
</div>
)
}
}
export default Clock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment