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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay