简体   繁体   中英

Convert DD-MM-YYYY to YYYY-MM-DD format using Javascript

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"
    }

This should do the magic

var date = "03-11-2014";
var newdate = date.split("-").reverse().join("-");

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

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.

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM