我有一个日期,格式是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日。我该如何解决这个问题?


当前回答

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

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

其他回答

如果你不反对使用库,你可以像这样使用Moments.js库:

var now = new Date(); var date弦=当下。 瓦尔·戴斯特时刻。格式(“YYYY-MM-DD HH: mm: ss”); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js " > < / >

简单地使用这个:

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

简单又甜蜜;)

我有一个关于这个问题的提纲

dateInstance.toLocaleDateString().replaceAll("/", "-").split("-").reverse().join("-");

你可以:

函数formatDate(日期){ var d = new Date(日期), 月= " + (d.getMonth() + 1) ", day = " + d.getDate(), year = d.g getfullyear (); 如果(月。长度< 2) 月= '0' +月; 如果一天。长度< 2) Day = '0' + Day; 返回[年,月,日].join('-'); } console.log(formatDate('Sun May 11,2014'));

使用的例子:

console.log(formatDate('Sun May 11,2014'));

输出:

2014-05-11

JSFiddle的演示:http://jsfiddle.net/abdulrauf6182012/2Frm3/

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

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));