Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

javascript - Convert ISO 8601 time date into plain English

How can I manipulate a date time in the format below (I believe it is ISO 8601 format) with JavaScript?

2010-01-13T18:31:16Z

I'd like to output as dd/mm/yyyy hh:mm:ss.

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you really want plain English, why not convert the string to a Date and call date.toLocaleString(), or toUTCString() if you want GMT.

var time=new Date('2010-01-13T18:31:16Z').toLocaleString();

If you want to support IE8 and older browsers you'll need translate the string:

(function(){
    var D= new Date('2011-06-02T09:34:29+02:00');
    if(!D || +D!==1307000069000){
        Date.fromISO= function(s){
            var day, tz,
            rx=/^(d{4}-dd-dd([tT][d:.]*)?)([zZ]|([+-])(dd):(dd))?$/,
            p= rx.exec(s) || [];
            if(p[1]){
                day= p[1].split(/D/);
                for(var i=0,L=day.length;i<L;i++){
                day[i]=parseInt(day[i], 10) || 0;
                };
                day[1]-= 1;
                day= new Date(Date.UTC.apply(Date, day));
                if(!day.getDate()) return NaN;
                if(p[5]){
                    tz= (parseInt(p[5], 10)*60);
                    if(p[6]) tz+= parseInt(p[6], 10);
                    if(p[4]== '+') tz*= -1;
                    if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
                }
                return day;
            }
            return NaN;
        }
        // shim implemented;
    }
    else{
        Date.fromISO= function(s){
            return new Date(s);
        }
        //native ISO Date implemented;
    }
})()

var time= Date.fromISO('2010-01-13T18:31:16Z').toLocaleString();

returned value: (String) Wednesday, January 13, 2010 1:31:16 PM


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...