如何将Date对象格式化为字符串?
当前回答
Javascript Intl.DateTimeFormat方法提供了一种格式化日期的方便方法。
以下是如何构建所需格式:
常量日期=新日期(“2010-08-10”);let d=新Intl.DateTimeFormat('en-GB',{年:“数字”,月:“短”,日:“2位数”}).format(日期).split(“”).join(“-”);console.log(d);
其他回答
受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了一个令人震惊的想法:
var D=Date().toString().split(“”);console.log(D[2]+“-”+D[1]+“-“+D[3]);
如果您已经在项目中使用ExtJS,则可以使用Ext.Date:
var date = new Date();
Ext.Date.format(date, "d-M-Y");
返回:
"11-Nov-2015"
在现代浏览器(*)中,您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
如果今天(1月24日)执行输出ᵗʰ, 2016):
'24-Jan-2016'
(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间版本。
如果您已经在项目中使用jQuery UI,您可以这样做:
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
这里提供了一些可以使用的日期选择器日期格式选项。
Use:
thisDate = new Date(parseInt(jsonDateString.replace('/Date(', '')));
formattedDate = (thisDate.getMonth() + 1) + "/" + (thisDate.getDate()+1) + "/" + thisDate.getFullYear();
这采用JSON日期“/date(1429573751663)/”,并生成格式化字符串:
"4/21/2015"