jQuery/JS - How to compare two date/time stamps?

前端 未结 5 863
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 18:53

I have two date/time stamps:

d1 = 2011-03-02T15:30:18-08:00 
d2 = 2011-03-02T15:36:05-08:00

I want to be above to compare the two:

5条回答
  •  失恋的感觉
    2020-12-10 19:37

    var d1= '2011-03-02T15:30:18-08:00', d2= '2011-03-02T15:36:05-08:00'; Some browsers can convert an ISO string to a Date, with new Date or Date.parse.

    A lot of browsers in use today cannot-you may need to write your own conversion.

    This one seems to work, but it'll need refining. I added a shim for browsers that don't have an array.map, based on mozilla org's public code.

    Date.fromISO= function(s){
        var day, tz, 
        rx=  /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/, 
        p= rx.exec(s) || [];
        if(p[1]){
            day= p[1].split(/\D/).map(function(itm){
                return parseInt(itm, 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;
    }
    Array.prototype.map= Array.prototype.map || function(fun, scope){
        var L= this.length, A= [], i= 0;
        if(typeof fun== 'function'){
            while(i< L){
                if(i in this) A[i]= fun.call(scope, this[i], i, this);
                ++i;
            }
            return A;
        }
    }
    var d1= '2011-03-02T15:30:18-08:00', d2= '2011-03-02T15:36:05-08:00';
    alert(Date.fromISO(d1)-Date.fromISO(d2)+' milliseconds')
    

提交回复
热议问题