0

which is being used for editing records fetched via an API. In this there are 2 fields which date fields. The data coming from the API is in "2021-07-30T20:34:40.545Z" where as the input field is shows dd-mm-yyyy with calendar icon. All other text fields are showing but the date is not showing.

I have tried the following

<div className='col text-left'>
    <label htmlFor='RegistrationDate' className='text-left'>
            Registration Date
    </label>
    <input
        type='date'
        name='RegistrationDate'
        className='form-control'
        value={new Date(RegistrationDate).toLocaleDateString('en-GB')}
        onChange={handleChange}
    />
</div>
  • You're formatting it to a locale string `{new Date(RegistrationDate).toLocaleDateString('en-GB')` if you just want the iso string don't format it as a localeDateString. `{new Date(RegistrationDate).toISOString()}` – pilchard Jun 19 '22 at 09:40

2 Answers2

0

use 'toISOString().substring(0,10)' to get 'yyyy-mm-dd' and then pass that into value :

const RegistrationDate = new Date("2021-07-30T20:34:40.545Z")
.
.
.
<input
    type="date"
    name="RegistrationDate"
    className="form-control"
    value={RegistrationDate.toISOString().substring(0, 10)}
    onChange={handleChange}
  />
0

To convert a date to yyyy-mm-dd format, which is the only format accepted by the input date element, you can use the Swedish locale.

registrationDate.toLocaleDateString('sv-SE')

See: Format JavaScript date as yyyy-mm-dd

Nice Books
  • 1,675
  • 2
  • 17
  • 21
  • 1
    "sv-SE" is not a "locale", it's a language. The parameter is misnamed "locale" in ECMA-402. – RobG Jun 20 '22 at 11:25
  • @RobG would love to learn more about it. Any references ? – Nice Books Jun 20 '22 at 15:23
  • 1
    See [*ECMA-402*](https://www.ecma-international.org/publications-and-standards/standards/ecma-402/), in particular §9.1 refers to "*Unicode BCP 47 locale identifiers*", however the title for the [related IETF document](https://tools.ietf.org/search/bcp47) is "Tags for Identifying Languages". Wikipedia has a list of [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag). I have no idea why the authors of ECMA-402 persist with the error. – RobG Jun 21 '22 at 11:58