17

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
  • 261
  • 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

80

This should do the magic

var date = "03-11-2014";
var newdate = date.split("-").reverse().join("-");
Ehsan
  • 3,964
  • 5
  • 37
  • 58
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
  • 134,457
  • 30
  • 163
  • 204
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
  • 78,842
  • 31
  • 152
  • 211
0

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
  • 24,187
  • 16
  • 134
  • 150
  • 1
    Hi, welcome to StackOverflow. Please clarify the difference between this and the accepted answer. Thank you. – MandyShaw Sep 24 '18 at 21:12
-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
  • 865
  • 1
  • 8
  • 18
  • 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