65

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>
    );
}
4
  • Are you bundling with webpack or browserify? Commented Jun 23, 2016 at 13:35
  • Is moment installed to your app via npm? and if so, you just need to import it in and use it like you would in normal javascript Commented Jun 23, 2016 at 13:36
  • 1
    @DavinTryon I am using webpack Commented Jun 23, 2016 at 13:38
  • @erichardson30 How can I use moment js functions in HTML loop.? Commented Jun 23, 2016 at 13:38

13 Answers 13

125

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>
    );
}
...
Sign up to request clarification or add additional context in comments.

2 Comments

Agreed. Or if you don't want the moment code to be within the JSX, create a format date function that simply returns the new formatted date and from the JSX do <p>{this.formatDate(post.date)}</p>
Worked for me, the only thing I would say is import it as import * as moment from 'Moment'
20

I know, question is a bit old, but since am here looks like people are still looking for solutions.

I'll suggest you to use react-moment link,

react-moment comes with handy JSXtags which reduce a lot of work. Like in your case :-

import React  from 'react';
import Moment from 'react-moment';

exports default class MyComponent extends React.Component {
    render() {
        <Moment format="YYYY/MM/DD">{this.props.dateToFormat}</Moment>
    }
}

1 Comment

This adds an entirely additional package to the project increasing bundle size. Why not just do: <div>{moment(this.props.dateToFormat).format('YYYY/MM/DD')}</div> ?
15

I have Used it as follow and it is working perfectly.

import React  from 'react';
import * as moment from 'moment'

exports default class MyComponent extends React.Component {
    render() {
            <div>
              {moment(dateToBeFormate).format('DD/MM/YYYY')}
            </div>            
    }
}

Comments

6

If the other answers fail, importing it as

import moment from 'moment/moment.js'

may work.

Comments

5

run npm i moment react-moment --save

you can use this in your component,

import Moment from 'react-moment';

const date = new Date();
<Moment format='MMMM Do YYYY, h:mm:ss a'>{date}</Moment>

will give you sth like this :
enter image description here

1 Comment

This adds an entirely additional package to the project increasing bundle size. Why not just do: <div>{moment(this.props.dateToFormat).format('YYYY/MM/DD')}</div> ?
4

So, I had to format this Epoch Timestamp date format to a legit date format in my ReactJS project. I did the following:

  1. import moment from 'moment' -- given you have moment js installed via NPM, if not head to this link

  2. For Example :

    If I have an Epoch date timestamp like 1595314414299, then I try this in a console to see the result -

  var dateInEpochTS = 1595314414299
  var now = moment(dateInEpochTS).format('MMM DD YYYY h:mm A');
  var now2 = moment(dateInEpochTS).format('dddd, MMMM Do, YYYY h:mm:ss A');
  console.log("NOW");
  console.log(now);
  console.log("NOW2");
  console.log(now2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Expected Output

"NOW"
"Jul 21 2020 12:23 PM"
"NOW2"
"Tuesday, July 21st, 2020 12:23:34 PM"

Comments

2

in my case i want getting timeZone of several country ,first install moment js

npm install moment --save  

then install moment-timezone.js

npm install moment-timezone --save

then i import themn in my component like this

import moment from 'moment';
import timezone from 'moment-timezone'

then because iwant getting hour and minutes and second sepratly i do like this

<Clock minutes={moment().tz('Australia/Sydney').minute()} hour={moment().tz('Australia/Sydney').hours()} second={moment().tz('Australia/Sydney').second()}/>

Comments

2

If you are working with API, then you can use it as:

import moment from 'moment'
...

        this.state = {
            List: []
        };
    }


    componentDidMount() {
        this.getData();
    }
    // Show List
    getData() {
        fetch('url')
            .then((response) => {
                response.json()
                    .then((result) => {
                        this.setState({ List: result })
                    })
            })
    }
this.state.List = 
this.state.List.map(row => ({...row, dob: moment(row.dob).format("YYYY/MM/DD")}))

...

Comments

1

import moment to your project

 import moment from react-moment

Then use it like this

return(
<Moment format="YYYY/MM/DD">{post.date}</Moment>
);

2 Comments

Answers should contain a short explanation.
This adds an entirely additional package to the project increasing bundle size. Why not just do: <div>{moment(this.props.dateToFormat).format('YYYY/MM/DD')}</div> ?
1
 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).calendar()}</p>
                <p dangerouslySetInnerHTML={{__html: post.content}}></p>
                <hr />
            </div>
        )}
    </div>
   );
  }

Comments

1

To use momentjs in Reactjs , we need to use the "Formats dates,Relatives time, Calendar Time or Multiple Locale Support", according to your needs choose only one . Momentjs For examples:

 {orders.map((item) => (
      <Accordion defaultExpanded={true}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls='panel1a-content'
          id='panel1a-header'
        >
          <Typography className={classes.heading}>
            {moment(item.created).format('MMM Do YY')} return  // Aug 12th 21 --> using Format Dates

Comments

0

HERE YOU GO! (MAGIC SOLUTION) In order to have a placeholder you must set your state to null first in the SELECTED property so that placeholder would be displayed and after that state would be mount with date user will select from the input tag.

import React,{useState} from 'react'
function App(){
  const [startDate, setStartDate] = useState();
  
  return(
    <>
    <DatePicker
      placeholderText="Click to enter the start date"
      **selected={startDate===" " ? null : startDate}**
      onChange={(date) => new Date(setStartDate(date))}
      selectsStart
      startDate={startDate}
      endDate={endDate}
      
 
   />
)}

Comments

-1

I'm using moment in my react project

import moment from 'moment'

state = {
    startDate: moment()
};
render() {
    const selectedDate = this.state.startDate.format("Do MMMM YYYY");
    return(
     <Fragment>
       {selectedDate)
     </Fragment>
   );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.