I am new to Moment.js and using ReactJS (ES6) for my project. How can I use moment.js to format a date?
I want to format post.date
in the below mentioned loop.
render() { return ( <div> { this.props.data.map((post,key) => <div key={key} className="post-detail"> <h1>{post.title}</h1> <p>{post.date}</p> <p dangerouslySetInnerHTML={{__html: post.content}}></p> <hr /> </div> )} </div> ); }
The moment-timezone package is required to use the timezone related functions. Then import the package into your project. import React from 'react'; import Moment from 'react-moment'; import 'moment-timezone'; export default class App extends React. Component { ... }
For this, we'll be using a library called moment js. A lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.
Conclusion. MomentJS isn't completely gone yet. But on their website they suggest you look beyond Moment unless you fall into specific usecases. Luxon seems to be the biggest replacement for Moment that is futureproof for now.
Since you are using webpack you should be able to just import
or require
moment and then use it:
import moment from 'moment' ... render() { return ( <div> { this.props.data.map((post,key) => <div key={key} className="post-detail"> <h1>{post.title}</h1> <p>{moment(post.date).format()}</p> <p dangerouslySetInnerHTML={{__html: post.content}}></p> <hr /> </div> )} </div> ); } ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With