-2

I have a requirement where i need to convert the date format from

DD-MON-YY to YYYY-MM-DD in javascript.

I have used the function below

function SimpleDate(inputdate) {
    var outputdate = new Date(inputdate);
    console.log(outputdate);
    var Outputyear=outputdate.toDateString().substr(outputdate.toDateString().lastIndexOf(' ')+1,4);
    console.log(Outputyear);
    return Outputyear ;

}

SimpleDate('05-FEB-19')

can anyone help here.

When i am passing the date as below . I am getting SimpleDate('05/02/19')

i am getting 1919 as response.

2 Answers2

1

You could just do some string manipulation:

 "20" + input.split("/").reverse().join("-")
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

It might be something like:

let formattedTime = new Date( //2. Creates new date from string
   `05-FEB-19`.replace(/-/g, ` `) //1. replaces all '-' with space
).toLocaleString(`zu-ZA`); 

/* 3. Returns a string formated to a traditional South African formatting (
South African just because they use exactly the format that you described). */

console.log(formattedTime)// -> "2019-02-05 00:00:00"

What is cool in this approach is that .toLocaleString() can format date in whatever format you prefer.

In case you pass no argument to that, it formats time according to the format that the final user prefers.

For instance:

 new Date().toLocaleString(); //-> "١٩‏/٣‏/٢٠١٩ ٨:٢٧:٥٨ م" if your OS language is Arabic.

 new Date().toLocaleString(); //-> "19/3/2019 00:00:06" if your OS language is Spanish.

 new Date().toLocaleString(); //-> "19.3.2019, 00:00:06" if your OS language is German.
Igor Bykov
  • 2,532
  • 3
  • 11
  • 19