开发者

How to convert time / date with jquery/javascript?

I currently have this

last_modified = xhr.getResponseHeader('Last-Modified');

/* Last-Modified: Wed, 06 Apr 2011 20:47:09 GMT */

However, for the timeago plugin i need this format

<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>

What would开发者_开发技巧 be the most easy and bulletproof way to convert?


Try this using javascript as follows:

For the Title part:

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

For the "July 17, 2008" part:

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


Have a look at date.js. Might be a little more than you need but it is an awesome library. Code should look something like:

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")

EDIT: @Hasan has pointed out that the native Date object is capable of parsing the header text. For this simple task that is likely the best option.


// 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) returned value: (String) 2011-04-06T20:47:09Z

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜