如何使用Javascript将ISO 8601日期格式化为更可读的格式? [英] How can I format an ISO 8601 date to a more readable format, using Javascript?

查看:950
本文介绍了如何使用Javascript将ISO 8601日期格式化为更可读的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



日期是在 ISO 8601格式

  2015-11-09T10:46我要我的日期格式如下:






  09/11/2015 

然后,稍后,我想将它们插入到我的HTML中,如下所示:

  $(data).each(function() {
var html ='< randomhtml>'+ this.created_at +'< randomhtml>
$('#stream')。append(html);
});

有谁知道我可以如何将日期更改为正确的格式?

解决方案

最简单的方法是使用字符串

  $(data).each(function(){

var date = this.created_at.split('T')//分割在T - > [2015-11- 09,10:...]
.shift()//获取第一部分 - >2015-11-09
.split(' - ')//再次拆分on - - > [2015,11,09]
.reverse()//反转数组 - > [09,11,2015]
.join('/')//加入/ - >09/11/2015

var html ='< randomhtml>'+ date +'& randomhtml>';
$('#stream')。append(html);
});

因为它是一个UTC日期,只是传递它做 new Date() / code>将添加时区的差异,而不是总是输出正确的日期。

如果您需要验证日期,则会有用于检查有效的UTC日期的正则表达式。


I'm using an API to call a date from a post.

Dates are returned in ISO 8601 format :

2015-11-09T10:46:15.097Z

I want my dates to be formatted like this :

09/11/2015

Then, later, I want to insert them into my HTML, like this :

$(data).each(function(){
    var html = '<randomhtml> '+this.created_at+' <randomhtml>
    $('#stream').append(html);
});

Does anyone know how I can change my date to right format?

解决方案

The easiest would be to just work with the string

$(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);
});

As it's a UTC date, just passing it do new Date() would add the difference of the timezone, and not always output the correct date.
If you need to validate the date, there are regexes for checking valid UTC dates.

这篇关于如何使用Javascript将ISO 8601日期格式化为更可读的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆