js格式化日期yyyyMMdd

來源:互聯網
上載者:User

標籤:style   blog   color   使用   os   io   2014   for   

先來一個土方法:

<script>function getyyyyMMdd(){    var d = new Date();    var curr_date = d.getDate();    var curr_month = d.getMonth() + 1;     var curr_year = d.getFullYear();    String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;    String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;    var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;    return yyyyMMdd;}    </script>

其中,唯一的注意點就是擷取年份時不要寫成d.getYear()這樣你擷取過來的就是114這個值,這裡解釋一下,為什麼是114?

因為今年是2014年而使用getYear()你擷取的是2014-1900這個數值。看到1900我想你應該懂了(預設系統時間)。

第二種方法,通過使用prototype擴充Date的format方法,實現日期格式化:

<script>var xx = getyyyyMMdd();/**   * 日期格式化(原型擴充或重載)   * 格式 YYYY/yyyy/ 表示年份   * MM/M 月份   * dd/DD/d/D 日期   * @param {formatStr} 格式模版   * @type string   * @returns 日期文字   */  Date.prototype.format = function(formatStr){           var str = formatStr;           var Week = [‘日‘,‘一‘,‘二‘,‘三‘,‘四‘,‘五‘,‘六‘];           str=str.replace(/yyyy|YYYY/,this.getFullYear());          str=str.replace(/MM/,(this.getMonth()+1)>9?(this.getMonth()+1).toString():‘0‘ + (this.getMonth()+1));           str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():‘0‘ + this.getDate());          return str;   } alert(new Date().format("yyyy-MM-dd")); </script>

像今天2014-07-28那麼其也將輸去2014-07-28。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.