📝

【React】時計を表示する

2022/03/21に公開
import type { NextPage } from 'next'
import { useEffect, useState } from 'react';

const Home: NextPage = () => {
    const [nowFullTime, setNowFullTime] = useState("")

    function zeroPadding(num: number,length: number){
        return ('0' + num).slice(-length);
    }

    async function showClock(){
        const nowTime = new Date();
        const nowHour = nowTime.getHours();
        const nowMin  = nowTime.getMinutes();
        const nowSec  = nowTime.getSeconds();
        const msg =  zeroPadding(nowHour, 2) + ":" + zeroPadding(nowMin, 2) + ":" + zeroPadding(nowSec, 2);
        setNowFullTime(msg);
    }

    useEffect(()=>{
        setInterval(()=>{
            showClock()
        },1000);
    },[]);
    
  return (
    <>
        <div className="clock">{nowFullTime}</div>
    </>
  )
}

export default Home

Discussion