This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan
In this article, you are going to learn about how to format dates in ReactJS.
ReactJS is a JavaScript library that is used in the front-end to better the UI experience. With react you can do many interesting things. The most interesting part is that you can write JavaScript code here easily. You already know that JavaScript comes with a Date object. You may think that using this object you may easily format a date. But there’s some issue with that. Let’s see the current date by using the JavaScript Date object first.
const currentDate = new Date()
console.log(currentDate)
//Output: 2022-01-29T10:03:47.564Z
You can see that we are getting the current date with time and all other stuff but we don’t want this. We want a nicely formatted date and by using this Date object it will little bit confusing in react. In react we can use an amazing library named the moment. It is a JavaScript library that is used to format, manipulate dates, and by using this library we can easily format dates in react. Before doing that, let’s see the command of installing this package.
npm install --save moment
// or
npm install moment
Now, let’s see the below code example where we used the moment library for formatting dates in react.
import "./index.css"
import Moment from 'moment';
function App() {
const formatDate = Moment().format('DD-MM-YYYY')
return (
<div className='container'>
<h1>{formatDate}</h1>
</div>
);
}
export default App;
Here, we simply import the moment library and then use it within a formatDate variable. Here, in our case, the date will give output as day and then month and finally the year. Let’s check the output below:
You can see that we are getting a nicely formatted date and the implementation is very simple. If you want to format the date another way you can also do that and to do so all you need to do is to apply the particular format that you want to use. Let’s see an example of it.
const formatDate = Moment().format("MMM Do YY");
Here, you simply need to use this format if you want to see the output of the date format like this in replace of the previous format. Let’s see the output below
You can see that the date format has been changed and this is how you can format date in react by using the moment library. There are various types of date formats but it is not possible to give examples of each of them. The purpose of this article is how you can format date in react. To know more types of date formats you may visit the official site of momentjs
This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan
Md Niaz Rahman Khan | Sciencx (2022-01-30T16:56:43+00:00) How to format dates in ReactJS. Retrieved from https://www.scien.cx/2022/01/30/how-to-format-dates-in-reactjs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.