將new Date() 格式化為 ’2018-10-11‘ 的字符串格式


 

function dateToString( date , format ){ if(!date) return ""; if (!Common.type.isDate(date)) return ""; //詳見博客:常用類型判斷 format = format ? format : "y-m-d"; switch(format){ case "y-m": return date.getFullYear() + "-" + datePad( date.getMonth() + 1, 2 ); case "y-m-d": return date.getFullYear() + "-" + datePad( date.getMonth() + 1, 2 ) + "-" + datePad( date.getDate(), 2 ); case "h-m-s": return datePad( date.getHours(), 2 ) + ":" + datePad( date.getMinutes(), 2 ) + ":" + datePad( date.getSeconds(), 2); case "y-m-d-h-m-s": return date.getFullYear() + "-" + datePad( date.getMonth() + 1, 2 ) + "-" + datePad( date.getDate(), 2 ) + " " + datePad( date.getHours(), 2 ) + ":" + datePad( date.getMinutes(), 2 ) + ":" + datePad( date.getSeconds(), 2); } }

 function datePad(num, n){  
        if( ( num + "" ).length >= n )
        return num; //一位數
        return arguments.callee( "0" + num, n ); //兩位數
     }

 Common.type.isDate: function() {
        for (var b = 0, a = arguments.length; b < a; b++) {
            o = arguments[b];
            if (!(System.type.isObject(o) && o.constructor && (o.constructor.toString().indexOf("Date") > -1 || o instanceof Date))) {
                return false;
            }
        }
        return true;
     }

 

 

   例:

      var today = new Date();

    dateToString(today);  // '2017-10-11'

      dateToString(today,'y-m');  //'2017-10'

      dateToString(today,'y-m-d-h-m-s');  //'2017-10-11 16:42:59'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM