2
1

More than 1 year has passed since last update.

Reactで現在の日時を表示する機能を実装したのでまとめます。

Javascriptで使用できるDateオブジェクトが持つ値から日付と時刻の値を
それぞれ取得するメソッドを使用いたします。

//年の値を取得する
getFullYear	

//月の値を取得する
getMonth

//	日の値を取得する
getDate	

//曜日の値を取得する
getDay	

//時の値を取得する
getHours	

//分の値を取得する
getMinutes	

//秒の値を取得する
getSeconds	

//ミリ秒の値を取得する
getMilliseconds	

①useEffectで現在の日時を取得する。

②、①で取得した値をuseStateに保管する。

③、②で保管した日時を出力する。

実際のコード

import React, {useEffect, useState} from "react";
import Dropdown from "@/Components/Navgation/Dropdown";

export const MCNavigation = ({auth}) => {

    const [date, setDate] = useState([])
    const [time, setTime] = useState([])

    useEffect(() => {
        setInterval(() => {
        let d = new Date();
        let year = d.getFullYear();
        let month = d.getMonth() + 1;
        let day = d.getDate();
        let dayofweek = d.getDay();

        const dayname = ['日','月','火','水','木','金','土'];

        setDate(year + '年' + month + '月' + day + '日' + '[' + dayname[dayofweek] + ']');

        let hour = d.getHours().toString().padStart(2, '0');
        let minute = d.getMinutes().toString().padStart(2, '0');
        setTime(hour + ':' + minute);
        });

    },[])


    return (
            <p>{date}<span>{time}</span></p>
           
    );
}

表示結果
スクリーンショット_20230116_193938.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1