how to get formatted date time like 2009-05-29 21:55:57 using javascript?

前端 未结 10 1340
轮回少年
轮回少年 2021-02-01 14:33

when using new Date,I get something like follows:

Fri May 29 2009 22:39:02 GMT+0800 (China Standard Time)

but what I want is xxxx-xx-xx xx:xx:xx formatted time s

10条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 15:10

    Date.prototype.toUTCArray= function(){
        var D= this;
        return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
        D.getUTCMinutes(), D.getUTCSeconds()];
    }
    
    Date.prototype.toISO= function(t){
        var tem, A= this.toUTCArray(), i= 0;
        A[1]+= 1;
        while(i++<7){
            tem= A[i];
            if(tem<10) A[i]= '0'+tem;
        }
        return A.splice(0, 3).join('-')+'T'+A.join(':');
        // you can use a space instead of 'T' here
    }
    
    Date.fromISO= function(s){
        var i= 0, A= s.split(/\D+/);
        while(i++<7){
            if(!A[i]) A[i]= 0;
            else A[i]= parseInt(A[i], 10);
        }
        --s[1];
        return new Date(Date.UTC(A[0], A[1], A[2], A[3], A[4], A[5]));  
    }
    
       var D= new Date();
       var s1= D.toISO();
       var s2= Date.fromISO(s1);
       alert('ISO= '+s1+'\nlocal Date returned:\n'+s2);
    

提交回复
热议问题