我有一个日期,格式是2014年5月11日太阳。如何使用JavaScript将其转换为2014-05-11 ?

函数taskDate(dateMilli) { var d = (new Date(dateMilli) + ")。分割(' '); D [2] = D [2] + ','; 返回[d[0], d[1], d[2], d[3]]。加入(' '); } var datemilli =日期。解析(' 2014年5月11日'); console.log (taskDate (datemilli));

上面的代码给了我相同的日期格式,2014年5月11日。我该如何解决这个问题?


当前回答

const formatDate = d => [
    d.getFullYear(),
    (d.getMonth() + 1).toString().padStart(2, '0'),
    d.getDate().toString().padStart(2, '0')
].join('-');

您可以使用padstart。

padStart(n, '0')确保字符串中至少有n个字符,并在它前面加上'0',直到达到该长度。

Join('-')连接一个数组,在每个元素之间添加'-'符号。

getMonth()从0开始,因此是+1。

其他回答

我建议使用类似formatDate-js的东西,而不是每次都试图复制它。只需使用一个支持所有主要strftime操作的库。

new Date().format("%Y-%m-%d")

简单地使用这个:

var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

简单又甜蜜;)

以下是一些答案的组合:

var d = new Date(date);
date = [
  d.getFullYear(),
  ('0' + (d.getMonth() + 1)).slice(-2),
  ('0' + d.getDate()).slice(-2)
].join('-');

重新格式化日期字符串是相当简单的,例如。

var s = ' 2014年5月11日'; 函数reformatDate(s) { 函数z(n){return ('0' + n).slice(-2)} var月=[‘简’,2月,3月,4月,“可能”,“君”, 7月,8月,9月,10月,11月,12月的]; var b = s.split(/\W+/); 返回b[3] + '-' + z (months.indexOf (b [1] .substr .toLowerCase (0, 3) ())) + '-' + z (b [2]); } console.log (reformatDate (s));

toISOString()假设日期是本地时间并将其转换为UTC。您将得到一个不正确的日期字符串。

下面的方法应该返回您需要的内容。

Date.prototype.yyyymmdd = function() {         

    var yyyy = this.getFullYear().toString();                                    
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
    var dd  = this.getDate().toString();             

    return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

来源:https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/