Home > Blockchain >  How to show ISO date format in a date input field - React
How to show ISO date format in a date input field - React

Time:06-19

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>

CodePudding user response:

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}
  />

CodePudding user response:

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

  • Related