reactで現在日時を取得する方法

Reactで現在の日付を取得する方法はいくつかあります。

  1. Dateオブジェクトを使って現在の日付を取得する
const currentDate = new Date();
console.log(currentDate);
  1. ReactのuseStateフックとJavaScriptのDateオブジェクトを使用して、現在の日付を取得し、コンポーネントの状態に保存する。
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [currentDate, setCurrentDate] = useState('');
useEffect(() => {
const date = new Date();
setCurrentDate(date);
}, []);
return (
<div>
<p>{currentDate.toString()}</p>
</div>
);
};
export default MyComponent;
  1. 現在の日付を取得するには、Moment.js のようなサードパーティの日付ライブラリを使用します。

Moment.jsをインストールしてインポートする:

npm install moment

Moment.jsで現在の日付を取得します。

import React from 'react';
import moment from 'moment';
const MyComponent = () => {
const currentDate = moment().format('YYYY-MM-DD');
return (
<div>
<p>{currentDate}</p>
</div>
);
};
export default MyComponent;
bannerAds