我正在使用API从帖子中调用日期。
日期在ISO 8601 format中返回:
2015-11-09T10:46:15.097Z
我希望我的日期格式如下:
09/11/2015
然后,我想将它们插入我的HTML中,如下所示:
$(data).each(function(){
var html = '<randomhtml> '+this.created_at+' <randomhtml>
$('#stream').append(html);
});
有谁知道如何将我的日期更改为正确格式?
答案 0 :(得分:5)
最简单的方法是使用字符串
$(data).each(function(){
var date = this.created_at.split('T') // split on the "T" -> ["2015-11-09", "10:..."]
.shift() // get the first part -> "2015-11-09"
.split('-') // split again on "-" -> ["2015", "11", "09"]
.reverse() // reverse the array -> ["09", "11", "2015"]
.join('/') // join with "/" -> "09/11/2015"
var html = '<randomhtml> ' + date + ' <randomhtml>';
$('#stream').append(html);
});
由于它是一个UTC日期,只需传递它new Date()
就会增加时区的差异,而不是总是输出正确的日期。
如果您需要验证日期,则可以使用正则表来检查有效的UTC日期。
答案 1 :(得分:2)
这可以解决您的问题
var date = new Date('2015-11-09T10:46:15.097Z');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
输出将是&#34; 09/11 / 2015&#34;
答案 2 :(得分:1)
答案 3 :(得分:0)
使用您正在使用的源格式设置日期格式的最可靠方法是应用以下步骤:
new Date()
.getDate()
,.getMonth()
和.getFullYear()
分别获取日期,月份和年份下面的format
功能向您展示了组合这四个步骤的最佳方式:
var date = '2015-11-09T10:46:15.097Z';
function format(input) {
var date = new Date(input);
return [
("0" + date.getDate()).slice(-2),
("0" + (date.getMonth()+1)).slice(-2),
date.getFullYear()
].join('/');
}
document.body.innerHTML = format(date); // OUTPUT : 09/11/2015
(另见this Fiddle)。
虽然这种方法适用于所有浏览器,但如果您需要支持与IE8相同的浏览器,则需要在new Date(input)
之前执行额外步骤来解析ISO 8601格式。请参阅Javascript JSON Date parse in IE7/IE8 returns NaN上接受的答案,了解完全相同的功能。
您还可以使用内置的.toLocaleDateString
方法为您进行格式化。您只需要传递适当的区域设置和选项以匹配正确的格式,但遗憾的是,只有现代浏览器支持(*):
var date = '2015-11-09T10:46:15.097Z';
function format(input) {
return new Date(input).toLocaleDateString('en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
document.body.innerHTML = format(date); // OUTPUT : 09/11/2015
(另见this Fiddle)。
(*) According to the MDN,“现代浏览器”指Chrome 24 +,Firefox 29 +,IE11,Edge12 +,Opera 15+&amp; Safari nightly build
答案 4 :(得分:0)
重新格式化日期字符串的最简单,最可靠的方法是重新格式化字符串。因此,使用 split (或 match )来获取值并按照您想要的顺序返回它们,忽略您不需要的位,例如:
function isoToDMY(s) {
var b = s.split(/\D/);
return b[2] + '/' + b[1] + '/' + b[0];
}
document.write(isoToDMY('2015-11-09T10:46:15.097Z'));
如果您希望输出日期也考虑主机系统时区(例如2015-11-09T20:46:15Z,在UTC + 0530的时区将为2015-11-10T02:16:15Z)),然后你应该手动将其解析为Date对象,然后获取年,月和日值。
库可以帮助解析,但是解析和验证值的函数只有几行。