什么是生成日期的最佳方式,例如:2016年7月27日4:53:18在JavaScript中?Javascript - 生成日期的最佳方式,如2016年7月27日4:53:18
我想过连接字符串,但我很难找到如何获得特定缩略格式的月份(七月)。
在此先感谢! :)
什么是生成日期的最佳方式,例如:2016年7月27日4:53:18在JavaScript中?Javascript - 生成日期的最佳方式,如2016年7月27日4:53:18
我想过连接字符串,但我很难找到如何获得特定缩略格式的月份(七月)。
在此先感谢! :)
对于浏览器支持Date.prototype.toLocaleString()
:
var month = [];
for(var n = 0; n < 12; n++) {
month[n] = (new Date(0, n + 1)).toLocaleString("en", {month: "short"});
}
console.log(month);
或者与Intl.DateTimeFormat()
:
var month = [],
intl = new Intl.DateTimeFormat("en", {month: "short"});
for(n = 0; n < 12; n++) {
month[n] = intl.format(new Date(0, n + 1));
}
console.log(month);
注:new Date(0, n + 1)
在1900年,这是因为OK,我们只关心这里每月产生的日期。
最后,这应该是非常接近最终预期输出:
var intl = new Intl.DateTimeFormat(
"en-US",
{
month : "short",
day : "numeric",
year : "numeric",
hour : "numeric",
minute : "numeric",
second : "numeric"
}
);
console.log(intl.format(Date.now()));
@ Arnauld获得它:谢谢!我不知道你可以这样做:)太棒了。 – Rose
要获得缩写的月份,你可以使用下面的代码片段:
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
function monthShortFormat(d){
var t = new Date(d);
return t.getDate()+' '+monthShortNames[t.getMonth()]+', '+t.getFullYear();
}
您是否尝试过内置'Date'对象? – gcampbell
我认为连接是去这里的最佳方式! –
@gcampbell:是的,但似乎有一个getMonth()方法,该方法将月份返回为int(即:1月份为2),但我正在寻找一个缩写的月份,例如Jul,并且我不确定如何得到那个 – Rose