Moment.js with ReactJS (ES6)

ReactjsMomentjs

Reactjs Problem Overview


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>
    );
}

Reactjs Solutions


Solution 1 - Reactjs

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>
    );
}
...

Solution 2 - Reactjs

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>
    }
}

Solution 3 - Reactjs

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>            
    }
}

Solution 4 - Reactjs

If the other answers fail, importing it as

import moment from 'moment/moment.js'

may work.

Solution 5 - Reactjs

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

Solution 6 - Reactjs

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"

Solution 7 - Reactjs

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()}/>

Solution 8 - Reactjs

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")}))

...

Solution 9 - Reactjs

import moment to your project

 import moment from react-moment

Then use it like this

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

Solution 10 - Reactjs

 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>
   );
  }

Solution 11 - Reactjs

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

Solution 12 - Reactjs

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}
      
 
   />
)}

Solution 13 - Reactjs

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>
   );
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJahanzaib AslamView Question on Stackoverflow
Solution 1 - ReactjsDavin TryonView Answer on Stackoverflow
Solution 2 - ReactjsDave RanjanView Answer on Stackoverflow
Solution 3 - ReactjsAnup BangaleView Answer on Stackoverflow
Solution 4 - ReactjsmeesvandongenView Answer on Stackoverflow
Solution 5 - ReactjsAlex YaoView Answer on Stackoverflow
Solution 6 - ReactjsKshitij ZutshiView Answer on Stackoverflow
Solution 7 - Reactjsghazaleh javaheriView Answer on Stackoverflow
Solution 8 - ReactjsMuhammad AwaisView Answer on Stackoverflow
Solution 9 - ReactjsHarrison EkpobimiView Answer on Stackoverflow
Solution 10 - ReactjsRashmi SinghView Answer on Stackoverflow
Solution 11 - ReactjsStanley Pierre LouisView Answer on Stackoverflow
Solution 12 - ReactjsJamal AshrafView Answer on Stackoverflow
Solution 13 - ReactjsNikhilView Answer on Stackoverflow