KWeiss
KWeiss

Reputation: 3144

Extract the date format from react-intl

I have a component that uses a datepicker. The datepicker needs a dateFormat property that fits the momentjs pattern, for example 'DD.MM.YYYY' or 'MM/DD/YYYY'.

The date formatting is handled by react-intl. This works fine when converting from a date to a string (via formatDate). However, I need to retrieve the pattern as described above.

My goal is to do something like

dateFormat = this.props.intl.extractDateFormat() // returns 'DD.MM.YYYY'

I have found this similar question, but the only answer relies on parsing the string, which I cannot do, because I do not know whether Day or Month will come first in the formatted date.

If it is possible to convert this string to a date and somehow retrieve the format from momentjs, that would also be a good solution.

Upvotes: 2

Views: 2133

Answers (1)

KWeiss
KWeiss

Reputation: 3144

I was able to get the date format from react-intl. To do this, I defined an example date and had it formatted by react-intl, and then parsed the format by referring to the original string.

My component which is exported as injectIntl(Component) has this method:

deriveDateFormat = () => {
  const isoString = '2018-09-25' // example date!

  const intlString = this.formatDate(isoString) // generate a formatted date
  const dateParts = isoString.split('-') // prepare to replace with pattern parts

  return intlString
    .replace(dateParts[2], 'DD')
    .replace(dateParts[1], 'MM')
    .replace(dateParts[0], 'YYYY')
}

The date will e.g. be formatted to '09/25/2018', and this function would return 'MM/DD/YYYY', a format which can be used by Moment.js.
This function only works if you know that the month and day will always be displayed with two digits. It would fail if the format is something like 9/25/2018.

I have not found a way to extract the date format from react-intl directly.

Upvotes: 1

Related Questions