Javascript-将日期字符串格式化为YYYY-MM-DD

Javascript-将日期字符串格式化为YYYY-MM-DD,javascript,Javascript,我需要用精确格式将日期表示为字符串: 2015-01-20 我看到有一个date.toIsoFormatString(),但不确定在哪里或如何提供上面显示的格式 Here is my code: var future = new Date(); future.setDate(future.getDate() + 30); console.log(future); 现在,我希望future.toString()或future.toIsoFormatString()仅以YYYY

我需要用精确格式将日期表示为字符串:

 2015-01-20   
我看到有一个date.toIsoFormatString(),但不确定在哪里或如何提供上面显示的格式

 Here is my code:

 var future = new Date();
 future.setDate(future.getDate() + 30);
 console.log(future);
现在,我希望future.toString()或future.toIsoFormatString()仅以YYYY-MM-DD格式显示日期。

您可以使用库来显示格式化日期

没有momentJs的示例:

 myDate = new Date();
 myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDate() // 2015-1-31
moment().format("YYYY-MM-DD") // 2015-01-31
momentJs示例:

 myDate = new Date();
 myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDate() // 2015-1-31
moment().format("YYYY-MM-DD") // 2015-01-31

MomentJs还有许多其他有用的功能

IE>8,所有其他更新的浏览器都可以在本机上实现这一功能-

new Date().toISOString().slice(0,10);

有谁不能解决你的问题?没有。没有console.log(future.toString('yyyy-MM-dd');直接从这个答案中获得:Sun Mar 01 2015 15:01:59 GMT-0800(太平洋标准时间),但如果你能想到答案,请发布。否?继续挖吧……;)www.stackoverflow.com-->www.justkeepdigging.com?:)我想我喝了太多伏特加了…toISOString使用UTC,而OP似乎想要本地日期。这将为临近午夜的时区偏移周期生成错误的本地日期。