-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?

2
  • 3
    i suggest using momentjs to convert the data format. Commented Mar 26, 2017 at 17:25
  • 1
    You are massively overthinking this. var input = "26/03/2017".split('/'); var output = input[2]+'-'+input[1]+'-'+input[0]; Commented Mar 26, 2017 at 17:29

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Great, it worked! Thanks
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.