在React中獲取當前日期的方法有多種方式:
const currentDate = new Date();
console.log(currentDate);
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;
安裝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;