-3

What is the best way to change this date format(Y-m-d) to this date Format(d-m-Y) in DOM using javascript.

This is what I have now:

<html>
   <body>
     <div>2019-07-01</div>
     <input type="text" value="2019-05-01">
   </body>
</html>

This is the way I would like it to be:

 <html>
       <body>
         <div>01-07-2019</div>
         <input type="text" value="01-05-2019">
       </body>
    </html>
Kuya
  • 7,280
  • 4
  • 19
  • 31
EddyKim
  • 155
  • 1
  • 14
  • 1
    This involves DOM and string manipulations. Please [edit] your question and show some of your attempts, so we have something to work with. What do you mean by “the _best_ way”? The exact DOM manipulations depend on the exact HTML — is it always going to be a `value` attribute and a text node? Is it always going to be `
    `s and ``s?
    – Sebastian Simon Jul 19 '19 at 03:03

2 Answers2

1

Pass your string into the Date Object and get the day, month and year. Finally reformat as you expect.

const domObj = document.querySelector('input[type=text]') // An ID might be better. Here `input[type=text]` just for example.

const date = new Date(domObj.value)
let day = date.getDate()
let month = date.getMonth() + 1
let year = date.getFullYear()
 
// add a leading 0 if the number is less than 10. like 9 to 09
day < 10 && (day = `0${day}`)
month < 10 && (month = `0${month}`)

const newFormat = `${day}-${month}-${year}`

domObj.value = newFormat
console.log(newFormat)
<html>
   <body>
     <div>2019-07-01</div>
     <input type="text" value="2019-05-01">
   </body>
</html>
MH2K9
  • 11,951
  • 7
  • 32
  • 49
1

You can get the month, year and day of month from Date object and reorder, or you can use moment, or you can use an input of type="date". It depends on if you want to require external libraries or choose input[type="text"] vs input[type="date"].

document.getElementsByName('inputDate')[0].addEventListener('input', function (evt) {
  const inputDate = new Date(evt.target.value)
  const date = inputDate.getDate()
  const month = inputDate.getMonth() + 1 // Since getMonth() returns month from 0-11 not 1-12.
  const year = inputDate.getFullYear() 
  document.getElementById('converted').innerHTML = `${date}-${month}-${year}`
})
<html>
   <body>
     <div id="converted">2019-07-01</div>
     <input name="inputDate" type="text" value="2019-05-01">
   </body>
</html>