用JavaScript解析ISO 8601日期

需要有关将具有以下结构的ISO 8601日期转换为javascript的帮助/提示。

CCYY-MM-DDThh:mm:ssTZD

我想这样格式化日期:

January 28, 2011 - 7:30PM EST

我想保持此解决方案尽可能干净和最小。

回答:

datejs可以解析以下内容,您可能想尝试一下。

Date.parse('1997-07-16T19:20:15')           // ISO 8601 Formats

Date.parse('1997-07-16T19:20:30+01:00') // ISO 8601 with Timezone offset

表达式版本

x = "2011-01-28T19:30:00EST"

MM = ["January", "February","March","April","May","June","July","August","September","October","November", "December"]

xx = x.replace(

/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):\d{2}(\w{3})/,

function($0,$1,$2,$3,$4,$5,$6){

return MM[$2-1]+" "+$3+", "+$1+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6

}

)

结果

January 28, 2011 - 7:30PM EST

我将时区更改为EST,现在我关注了

x = "2011-01-28T19:30:00-05:00"

MM = {Jan:"January", Feb:"February", Mar:"March", Apr:"April", May:"May", Jun:"June", Jul:"July", Aug:"August", Sep:"September", Oct:"October", Nov:"November", Dec:"December"}

xx = String(new Date(x)).replace(

/\w{3} (\w{3}) (\d{2}) (\d{4}) (\d{2}):(\d{2}):[^(]+\(([A-Z]{3})\)/,

function($0,$1,$2,$3,$4,$5,$6){

return MM[$1]+" "+$2+", "+$3+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6

}

)

返回

January 28, 2011 - 7:30PM EST

基本上

String(new Date(x))

返回

Fri Jan 28 2011 19:30:00 GMT-0500 (EST)

正则表达式部分只是将上述字符串转换为您所需的格式。

January 28, 2011 - 7:30PM EST

以上是 用JavaScript解析ISO 8601日期 的全部内容, 来源链接: utcz.com/qa/433559.html

回到顶部