开发者

Javascript Timestamp from ISO8061

I'm having a bit of an issue when dealing with getting a timestamp from an iso8061 date. For some reason it work perfectly in Chrome, but causes an Invalid Date error in Firefox. The exact line is:

var date = new Date(time.replace(/-/g,"/").replace(/[TZ]/g," ")); 

I've tried passing the date through (as the var time) 20开发者_JS百科11-03-09T16:46:58+00:00, 2011-03-09T16:46:58+0000 and 2011-03-09T16:48:37Z as per the spec outlined http://www.jibbering.com/faq/#dates but I still can't seem to get it to work in firefox. In fact, the last method didn't work in either browser.

If anyone could help me turn this iso8061 date into a timestamp, that would be great.

Thanks, Angelo R.


take a look at JavaScript ISO8601/RFC3339 Date Parser:

their code:

Date.prototype.setISO8601 = function(dString){
    var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
    if (dString.toString().match(new RegExp(regexp))) {
        var d = dString.match(new RegExp(regexp));
        var offset = 0;
        this.setUTCDate(1);
        this.setUTCFullYear(parseInt(d[1],10));
        this.setUTCMonth(parseInt(d[3],10) - 1);
        this.setUTCDate(parseInt(d[5],10));
        this.setUTCHours(parseInt(d[7],10));
        this.setUTCMinutes(parseInt(d[9],10));
        this.setUTCSeconds(parseInt(d[11],10));
        if (d[12]) {
            this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
        }
        else {
            this.setUTCMilliseconds(0);
        }
        if (d[13] != 'Z') {
            offset = (d[15] * 60) + parseInt(d[17],10);
            offset *= ((d[14] == '-') ? -1 : 1);
            this.setTime(this.getTime() - offset * 60 * 1000);
        }
    }
    else {
        this.setTime(Date.parse(dString));
    }
    return this;
};

and then you can use it this way:

var today = new Date();
today.setISO8601('2008-12-19T16:39:57.67Z');

probably not that comfortable, but you can rewrite this function, or write another one which will return date based on ISO-8601 format


The way that the Date constructor handles string arguments differs across browsers. As the first answer to this question points out, IE recognizes hyphens, but Firefox does not, as just one example.

It's probably best to use the constructor that expects individual date parts.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜