Sometimes, we want to format a date inside a React component.
In this article, we’ll look at how to format a date inside a React component.
Format a Date Inside a React component
To format a date inside a React component, we can use the toLocaleDateString
method.
For instance, we write:
import React from "react";
const DATE_OPTIONS = {
weekday: "short",
year: "numeric",
month: "short",
day: "numeric"
};
export default function App() {
return (
<div>{new Date(2021, 1, 1).toLocaleDateString("en-US", DATE_OPTIONS)}</div>
);
}
We have the DATE_OPTIONS
object with the weekdayproperty set to
‘short’` to show the abbreviation of the day of the week.
year
is set to 'numeric'
to show the year as a 4 digit number.
month
is set to 'short'
to show the abbreviation of the month.
And year
is set to 'numeric'
to show the year as a number.
Then we call toLocaleDateString
with the locale string and the DATE_OPTIONS
object to return the date string formatted with the specified format options.
As a result, we see:
Mon, Feb 1, 2021
displayed on the screen.
Conclusion
To format a date inside a React component, we can use the toLocaleDateString
method.