DEV Community

Dhiman_aman
Dhiman_aman

Posted on

5

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay