22

I'm trying to convert date format (DD-MM-YYYY) to (YYYY-MM-DD).i use this javascript code.it's doesn't work.

 function calbill()
    {
    var edate=document.getElementById("edate").value; //03-11-2014

    var myDate = new Date(edate);
    console.log(myDate);
    var d = myDate.getDate();
    var m =  myDate.getMonth();
    m += 1;  
    var y = myDate.getFullYear();

        var newdate=(y+ "-" + m + "-" + d);

alert (""+newdate); //It's display "NaN-NaN-NaN"
    }
KT1
  • 311
  • 2
  • 4
  • 13
  • 2
    Do not rely on what `Date` constructor will parse. Never. Seriously. Don't do it. Also read [this](http://stackoverflow.com/a/25865621/1207195) and check some other linked posts. – Adriano Repetti Nov 23 '14 at 08:49
  • 1
    Ok, what does "it doesn't work" mean? What does it do instead? – JJJ Nov 23 '14 at 08:50
  • @Juhana when i add "alert (""+newdate);".it's Display "NaN-NaN-NaN" – KT1 Nov 23 '14 at 08:59

5 Answers5

100

This should do the magic

var date = "03-11-2014";
var newdate = date.split("-").reverse().join("-");
Ehsan
  • 4,334
  • 7
  • 39
  • 59
3

Don't use the Date constructor to parse strings, it's extremely unreliable. If you just want to reformat a DD-MM-YYYY string to YYYY-MM-DD then just do that:

function reformatDateString(s) {
  var b = s.split(/\D/);
  return b.reverse().join('-');
}

console.log(reformatDateString('25-12-2014')); // 2014-12-25
RobG
  • 142,382
  • 31
  • 172
  • 209
1

You can use the following to convert DD-MM-YYYY to YYYY-MM-DD format using JavaScript:

var date = "24/09/2018";
date = date.split("/").reverse().join("/");

var date2 = "24-09-2018";
date2 = date.split("-").reverse().join("-");

console.log(date); //print "2018/09/24"
console.log(date2); //print "2018-09-24"
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
0

You just need to use return newdate:

function calbill()
{
var edate=document.getElementById("edate").value;

var myDate = new Date(edate);
console.log(myDate);
var d = myDate.getDate();
var m =  myDate.getMonth();
m += 1;  
var y = myDate.getFullYear();

    var newdate=(y+ "-" + m + "-" + d);
  return newdate;
}

demo


But I would simply recommend you to use like @Ehsan answered for you.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
-1

First yo have to add a moment js cdn which is easily available at here

then follow this code

moment(moment('13-01-2020', 'DD-MM-YYYY')).format('YYYY-MM-DD');
// will return 2020-01-13

Rinku Choudhary
  • 1,529
  • 1
  • 13
  • 22
  • 1
    This requires an external library. There's no mention of that. There's also no explanation. This answer is unconsidered "unhelpful" on stackoverflow. – Onimusha Nov 22 '20 at 18:08