import * as React from "react"; import "../style/clock.scss"; interface State { time: string; date: string; } class Clock extends React.Component<{}, State> { private interval: NodeJS.Timeout; constructor(props) { super(props); this.state = { time: "", date: "" }; } updateTime() { const now = new Date(); // Is there a native function for formatting time ?? this.setState({ time: `${this.zeroPad(now.getHours(), 2)}:${this.zeroPad(now.getMinutes(), 2)}` }); } updateDate() { const now = new Date(); this.setState({ date: `${now.toDateString()}` }); } zeroPad(number: number, pad: number): string { const length = number.toString().length; if (length < pad) { return "0".repeat(pad - length) + number.toString(); } else { return number.toString(); } } startTimer() { this.interval = setInterval(()=>{ this.updateTime(); // This will change only if the tab stays open after midnight. But still, lets cover that this.updateDate(); },1000); } componentDidMount() { this.updateTime(); this.updateDate(); this.startTimer(); } componentWillUnmount(){ clearInterval(this.interval); } render(): JSX.Element { return
{this.state.time}
{this.state.date}
; } } export default Clock;