-3

I need to convert a data from this format 26/03/2017 in this format 2017-03-26, starting from picking data from a form id.

I've tried like this, but I'm lost now.. any help?

var dataform = "26/03/2017";
var dataora = new Date(dataform);


var G = dataora.getDate(dataform);
var M = (dataora.getMonth(dataform) + 1);


if (G < 10)
{
 var mm = "0" + dataora.getDate(dataform);
}
else
{
 var mm = dataora.getDate(dataform);
}

if (M < 10)
{
 var gg = "0" + (dataora.getMonth(dataform) + 1);
}
else
{
 var gg = (dataora.getMonth(dataform) + 1);
}

var aa = dataora.getFullYear(dataform);

var data = aa + "-" + mm + "-" + gg;

console.log(data);
console.log("Year "+aa);
console.log("Month "+mm);
console.log("Day "+gg);

Output is:

2019-03-02

Year 2019
Month 03
Day 02

Where am I wrong?

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 3
    i suggest using [momentjs](https://momentjs.com) to convert the data format. – Paolo Mar 26 '17 at 17:25
  • 1
    You are massively overthinking this. `var input = "26/03/2017".split('/'); var output = input[2]+'-'+input[1]+'-'+input[0];` – JJJ Mar 26 '17 at 17:29

2 Answers2

1
  • Split the date using split function with /.
  • Reverse it using the reverse function
  • Then Join it using the join function with -.

That's it.

var date="26/03/2017";
date=date.split("/").reverse().join("-");
console.log(date);
Sagar V
  • 12,158
  • 7
  • 41
  • 68
0

Where am I wrong?

Don't use the Date constructor (or Date.parse) to parse strings, as it's largely implementation dependent and varies across hosts. See Why does Date.parse give incorrect results?

Per Sagar V's answer, just reformat the string.

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209