Convert mm/dd/yyyy to yyyy-mm-dd

Viewed 20366

I need to convert a date like this, 03/07/2016 to a date format like, 2016-03-07.

How can I do this using javascript or jquery?

5 Answers

If you want to avoid using regular expressions, manipulating strings, or loading an entire library like moment, you can do this in one line by creating a new JavaScript Date object with the date you want formatted and calling its toLocaleDateString method with a compatible locale, such as fr-CA.

new Date('01/31/2020').toLocaleDateString('fr-CA') // "2020-01-31"

Supported in all modern browsers.


Credit: https://masteringjs.io/tutorials/fundamentals/date_format

const date = new Date();
const convertedDate = date.toLocalDateString('en-IN').split('/').reverse().join('-');

console.log(convertedDate);

Please follow the below method. The trick is to use the unshift property.

function formatDate(__d){
    if(__d.indexOf('/')){
      var a = __d.split('/')
      var b = a.pop()
      a.unshift(b)
   }
  return a.join('-')
}
Related