1

I am trying to format date time string value using react-moment in my react component. moment returns an object but i need a string value from moment. This is the code I have:

import Moment from 'react-moment';

const dateToFormat = '2015-08-31T16:14:00.000Z';

const datetm = <Moment format="dddd, MMMM Do YYYY, h:mm a" date = {dateToFormat} />;

datetm always return object but I want it to be string. Does moment has any attribute that can be set to get string value instead an object?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user8870784
  • 23
  • 1
  • 5
  • 2
    You can just use the format object to set it as a string `moment(dateToFormat).format('dddd, MMMM Do YYYY');` – Matty Nov 01 '17 at 22:04
  • https://www.npmjs.com/package/react-moment#formatting – Karl Reid Nov 01 '17 at 22:04
  • I think you can get reference from below https://stackoverflow.com/questions/45809080/how-to-convert-moment-date-to-a-string-and-remove-the-moment-object – Ahsan Smartoo Nov 01 '17 at 22:07
  • 2
    If you don't want a React element why are you creating one? – Felix Kling Nov 01 '17 at 22:07
  • when i use moment(dateToFormat).format('dddd, MMMM Do YYYY'); it throws error 'Cannot call a class as a function'. @fleix I have to format a dateToFormat value in different formats – user8870784 Nov 01 '17 at 22:18
  • 1
    I think you are using the wrong library. What you need for this is http://momentjs.com/ . react-moment is a react wrapper for momentjs. – Artur Nista Nov 01 '17 at 22:44
  • *"I have to format a dateToFormat value in different formats"* That is not a reason to create or not create a React component. You are either using React and want to render a date with React or you don't. – Felix Kling Nov 01 '17 at 22:48

1 Answers1

2

You are using react-moment which is a wrapper component for the moment js. You can you use this as a react component. but not as normal use. Instead use moment js.

install the moment js package using npm.

> npm install --save moment

in your js file

> import moment from 'moment';

then use moment instance.

> moment(<date string>/<date object>/<moment object>).format(<format string>)