如何用jquery / javascript转换时间/日期?

我现在有这个

last_modified = xhr.getResponseHeader('Last-Modified'); /* Last-Modified: Wed, 06 Apr 2011 20:47:09 GMT */ 

但是,对于timeago插件,我需要这种格式

 July 17, 2008 

什么是最容易和防弹的转换方式?

使用javascript尝试如下:

对于标题部分:

  var dateObj = new Date(last_modified); var newDate = dateObj .getFullYear() + "-" + dateObj.getMonth() + "-" + dateObj.getDate() + "T" + dateObj.getHours() + ":" + dateObj.getMinutes() + ":" + dateObj.getSeconds() + "Z"; 

对于“2008年7月17日”部分:

  var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var dateObj = new Date(last_modified); var anotherDate = m_names[dateObj.getMonth()] + " " + dateObj.getDate() + ", " + dateObj.getFullYear(); 

看看date.js。 可能比你需要的多一点,但它是一个很棒的库。 代码应该类似于:

 last_modified = xhr.getResponseHeader('Last-Modified'); last_modified_date = last_modified.split(': ')[1]; date = Date.parse(last_modified_date); date.toString("yyyy-MM-ddTHH:mm:ssZ") 

编辑: @Hasan已指出本机Date对象能够解析标题文本。 对于这个简单的任务,这可能是最好的选择。

 // Some browsers can natively return an ISO date string, but a lot cannot. // And some insist on adding the milliseconds to the string- // '2011-04-06T20:47:09.000Z' function isoString(date){ var A, T, D= new Date(date); if(D){ // uncomment next line if you allow msecs in string // if(D.toISOString) return D.toISOString(); A= [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(), D.getUTCMinutes(), D.getUTCSeconds()]; A[1]+= 1; for(var i= 0; i<6; i++) if(A[i]<10) A[i]= '0'+A[i]; T= A.splice(3, A.length); return A.join("-")+("T" + T.join(":")+ "Z"); } // throw 'bad date'; } 

var str ='Wed,06 Apr 2011 20:47:09 GMT';

isoString(str)返回值:(String) 2011-04-06T20:47:09Z