Time/Date in React using setInterval

new Date()

new Date() creates a new JavaScript Date instance.

new Date()
=> Sat Aug 05 2017 01:33:05 GMT-0400 (EDT)

This is different from Date() which returns a string.

Date()
=> 'Sat Aug 05 2017 01:33:05 GMT-0400 (EDT)'

Since it is an object, it can be store in a variable.

var currentTimeDate = new Date()

Date.prototype Methods

All Date instances inherit from Date.prototype which gives you a variety of methods such as getHours() or getMonth().

currentTimeDate.getDay()
=> 6
(Returns the day of the week (0-6))
currentTimeDate.getMonth()
=> 7
(Returns the month (0-11))
currentTimeDate.getDate()
=> 5
(Returns the day of the month (1-31))
currentTimeDate.getFullYear()
=> 2017
(Returns the year (4 digits for 4-digit years))
currentTimeDate.getHours()
=> 2
(Returns the hour (0-23))
currentTimeDate.getMinutes()
=> 43
(Returns the minutes (0-59))
currentTimeDate.getSeconds()
=> 14
(Returns the seconds (0-59))

setInterval()

setInterval is a method that calls a function repeatedly with an established time delay.

For example, let’s say that we have a simple function:

function hello() {
console.log("Hello World")
}

We all know what would happen when we call that function.

hello()
=> "Hello World"

What if we call this function repeatedly using the setInterval method?

setInterval(hello, 1000)
=> "Hello World"
=> "Hello World"
=> "Hello World"
=> "Hello World"
=> "Hello World" (Will call the hello function every second)

The setInterval method must take a function as the first argument and an integer that represents the delay as the second argument. Every 1000 delay is 1 second.

Time and Date in React

Now that you know how Date() and setInterval() works, you can implement this in your React app. Since getMonth() and getDay() returns in integer, you would have to establish their string formats in an array.

import React, {Component} from 'react'
import '../styles/TimeDate.css';
class TimeContainer extends Component {
  constructor() {
super()
    let d = new Date()
this.state = {
day: d.getDay(),
month: d.getMonth(),
date: d.getDate(),
year: d.getFullYear(),
time: d.toLocaleTimeString()
}
    this.countingSecond = this.countingSecond.bind(this)
}
  countingSecond() {
let d = new Date()
this.setState({
day: d.getDay(),
month: d.getMonth(),
date: d.getDate(),
year: d.getFullYear(),
time: d.toLocaleTimeString()
})
}
  componentWillMount() {
setInterval(this.countingSecond, 1000)
}
  render() {
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "November", "December"]
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  return (
<div className='timeclock-main'>
<h3 className='timeclock-text'>{days[this.state.day]}, {months[this.state.month]} {this.state.date}, {this.state.year} {this.state.time}</h3>
</div>
)
}
}
export default TimeContainer

Now you have a clock live on your website!