Solution
To display the date in React, we have the following ways
- Using the
toString()
Method, it will convert the date object into a string and print it in the UI. - Using the
toLocaleDateString()
method, it will convert the date object into a string with a format in US style. - Using the
toDateString()
method, it will convert the date object into a string formatted. - Using the
moment
method, will allow the format date in your desired format.
Snippet
In this snippet, we will see a short example of all the above discuss methods to show date objects in React UI.
<p>Display date object</p>
<p>{date.toString()}</p> // Fri Dec 16 2022 21:27:53 GMT+0530 (India Standard Time)
<p>Using toLocaleDateString</p>
<p>{date.toLocaleDateString()}</p> // 12/16/2022
<p>Using toDateString</p>
<p>{date.toDateString()}</p> // Fri Dec 16 2022
<p>Using moment</p>
<p>{moment(date).format("DD/MM/YYYY")}</p> // 16/12/2022
Example
In this example, we will use all the above methods to display dates in react UI using react state and date formatting packages.
Let’s start coding…
import React, { useState } from "react";
import moment from "moment";
function CurrentDate() {
const [date, setDate] = useState(new Date());
return (
<>
<p>Display date object</p>
<p>{date.toString()}</p>
<p>Using toLocaleDateString</p>
<p>{date.toLocaleDateString()}</p>
<p>Using toDateString</p>
<p>{date.toDateString()}</p>
<p>Using moment</p>
<p>{moment(date).format("DD/MM/YYYY")}</p>
</>
);
}
export default CurrentDate;
Output