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

2020-08-13 02:48发布

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

标签: javascript
5条回答
forever°为你锁心
2楼-- · 2020-08-13 03:08

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
查看更多
一夜七次
3楼-- · 2020-08-13 03:12

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.

查看更多
贪生不怕死
4楼-- · 2020-08-13 03:13
moment(moment('13-01-2020', 'DD-MM-YYYY')).format('YYYY-MM-DD');   // will return 2020-01-13
查看更多
ゆ 、 Hurt°
5楼-- · 2020-08-13 03:18

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"
查看更多
成全新的幸福
6楼-- · 2020-08-13 03:25

This should do the magic

var date = "03-11-2014";
var newdate = date.split("-").reverse().join("-");
查看更多
登录 后发表回答