如何将Date对象格式化为字符串?


当前回答

试试看:

函数init(){var d=新日期();var day=d.getDate();var x=d.toDateString().substr(4,3);var year=d.getFullYear();document.querySelector(“#mydate”).innerHTML=day+'-'+x+'-'+年;}window.onload=init;<div id=“mydate”></div>

其他回答

我知道有人可能会说这是一个愚蠢的解决方案,但它确实做到了从日期字符串中删除不必要的信息。

yourDateObject生成:

2017年12月13日星期三20:40:40 GMT+0200(欧洲东部时间)

yourDateObject.toString().sslice(0,15);生产:

2017年12月13日星期三

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js2010年8月10日为:

var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log(clock.day + '-' + str + '-' + clock.year); //gets you 10-Aug-2010



如果您已经在项目中使用ExtJS,则可以使用Ext.Date:

var date = new Date();
Ext.Date.format(date, "d-M-Y");

返回:

"11-Nov-2015"

受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了一个令人震惊的想法:

var D=Date().toString().split(“”);console.log(D[2]+“-”+D[1]+“-“+D[3]);

使用ECMAScript Edition 6(ES6/ES2015)字符串模板:

let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;

如果需要更改分隔符:

const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);