Search code examples
javascriptreactjsdate-fns

How to auto-refresh time in React when using 'date-fns' library


I am working on my personal Portfolio using React and I want to add a statement on the landing page that displays my local time and timezone to recruiters, as seen below: Time

I have implemented this using the date-fns library but I am currently facing one issue. As time goes by, the time values on the screen stay constant and do not update themselves automatically. As we speak, it is currently 16:58 but the time still shows 16:47. I have to do a manual refresh for the updated time values to show. I want to implement this in such a way that the time will update every 60 seconds and show the current time always.

I wrote this Class component to implement the feature:

export class Time extends Component {

  constructor() {
  super();
    var today = new Date();

    var time = format(today, 'HH:mm')

    this.state = {

      currentTime: time

    }

  }

   
  render() {
    return (
      <div className="time">
        <p>
          My Local Time is { this.state.currentTime } GMT +3
        </p>
      </div>
    );
  }

}

setInterval(Time, 60000);

What could I do to make this possible?


Solution

  • I tried using the solution provided Luke-shang-04 but I ran into issues with declaration of the intervalId variable. I therefore resorted to using React Hooks and converted this component into a Functional component.

    The code below works:

    export const Time = () => {
       
    
      const [time, setTime] = useState(new Date());
    
      useEffect(
        () => {
          const intervalId = setInterval(() => {
          
            setTime(new Date());
          }, 60000);
          return () => {
            clearInterval(intervalId)
          }
        } 
      )
    
      return(
        <div>
          <p>{`My local time is ${format(time, 'HH:mm')} GMT+3`} </p>
        </div>
      )
    
    }