使用 Javascript 将 DD-MM-YYYY 转换为 YYYY-MM-DD 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27087128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:41:28  来源:igfitidea点击:

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

javascript

提问by KT1

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

我正在尝试将日期格式 (DD-MM-YYYY) 转换为 (YYYY-MM-DD)。我使用此 javascript 代码。它不起作用。

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

回答by Ehsan

This should do the magic

这应该很神奇

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

回答by RobG

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:

不要使用 Date 构造函数来解析字符串,它非常不可靠。如果您只想将 DD-MM-YYYY 字符串重新格式化为 YYYY-MM-DD,那么只需执行以下操作:

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

console.log(reformatDateString('25-12-2014')); // 2014-12-25

回答by Bhojendra Rauniyar

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.

但我只是建议您使用@Ehsan 为您回答的问题。

回答by Guilherme Rodrigues

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

您可以使用以下内容使用 JavaScript 将 DD-MM-YYYY 转换为 YYYY-MM-DD 格式:

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"

回答by rinku Choudhary

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