DEV Community

Dhiman_aman
Dhiman_aman

Posted on

Use Live Time/Date in the ReactJS

  • make the object of the Date() Method

const date = new Date();

  • use effect to display the live time

useEffect(() => {
setInterval(() => {
setDateState(new Date());
}, 1000);
}, []);

  • give the some parameters in the return value {dateState.toLocaleString("en-US", { hour: "numeric", minute: "numeric", second: "2-digit", hour12: true, })}
  • Complete Code of Time/Date
import React from "react";
import { useState, useEffect } from "react";

const ClockAPI = () => {
  const [dateState, setDateState] = useState(new Date());

  const t = new Date();
  const c = t.getHours() - 12;
  useEffect(() => {
    setInterval(() => {
      setDateState(new Date());
    }, 1000);
  }, []);

  return (
    <>
      <h1 className="mb-4 text-6xl font-extrabold tracking-tight leading-none  text-white-900 md:text-5xl lg:text-6xl dark:text-white">
        {dateState.toLocaleString("en-US", {
          hour: "numeric",
          minute: "numeric",
          second: "2-digit",
          hour12: true,
        })}
      </h1> 

    </>
  );
};

export default ClockAPI;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)