React-datepicker: [Help Wanted] Format date based on given locale

Created on 13 Dec 2018  路  3Comments  路  Source: Hacker0x01/react-datepicker

I was wondering if there is a way to format date and time based on the locale prop. For example:

| locale | dateFormat | timeFormat |
|:-------:|:-------------:|------------|
| en-US | MM/dd/yyyy | hh:mm aa |
| pt-BR | dd/MM/yyyy | HH:mm |

Expected behavior

Automatically uses the corresponding date and time formats when passing a locale prop.

Actual behavior

Even using the locale prop I need to pass the corresponding date and time formats

Steps to reproduce

const DatePicker = require('./index.js').default

class DatePickerExample extends React.Component {
  constructor() {
    super()
    this.state = {
      startDate: new Date(),
      locale: 'pt-BR',
    }

    this.handleDateChange = this.handleDateChange.bind(this)
  }

  handleDateChange(date) {
    this.setState({
      startDate: date,
    })
  }

  render() {
    return (
      <DatePicker
        value={this.state.startDate}
        onChange={this.handleDateChange}
        useTime={true}
        locale={this.state.locale}
      />
    )
  }
}

;<DatePickerExample />

I expected to see the date formated as dd/MM/yyyy HH:mm but it remained the default MM/dd/yyyy hh:mm aa

Most helpful comment

You can do:

  <DatePicker
   selected={this.state.startDate}
   onChange={this.handleDateChange}
+  dateFormat="P"
   locale={this.state.locale} />

All 3 comments

You can do:

  <DatePicker
   selected={this.state.startDate}
   onChange={this.handleDateChange}
+  dateFormat="P"
   locale={this.state.locale} />

Thank you @klzns ! It's exactly what I was looking for.

@klzns
I have a related question. Is there a way to do the same thing for placeholderText attribute such that placeholder displays a hint for the localized date format?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sarav1234 picture sarav1234  路  3Comments

jcabrerazuniga picture jcabrerazuniga  路  3Comments

hoodsy picture hoodsy  路  3Comments

ali-master picture ali-master  路  3Comments

kkras3 picture kkras3  路  3Comments