TAGS :Viewed: 5 - Published at: a few seconds ago

[ How to change the display format of date in react-intl? ]

I need to display the date using different separators using react-intl. So far I have this

const date = new Date("2016-08-12T16:59:02.013+02:00");
...
return() {
   render(
      <FormattedDate
            value={date}
            year='numeric'
            month='numeric'
            day='numeric'
          />
   )
}

This renders the date 8/12/2016, but I need to show it like this 8-12-2016. How can this be done with FormattedDate? Or should I use a different approach?

Answer 1


First, import the hoc from react-intl package:

import {injectIntl} from 'react-intl'

then apply it to your component:

injectIntl(YourReactComponent)

It will give you access to the formatDate method via the props in YourReactComponent. The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date:

  const stringDate = this.props.intl.formatDate(date, // your date variable
            {
                year:'numeric',
                month:'numeric',
                day:'numeric'
            })

stringDate now contains 8/12/2016, you can modify it as you like:

const stringWithHyphens = stringDate.replace(/\//g, "-"); // replacing all '/'s with '-'s