Javascript:日期文字(DateStr)與日期對象(Date)之間的轉換

來源:互聯網
上載者:User

今天做項目,遇到一個需要把日期文字(如:2009-02-03)轉換成Javascript中日期對象Date,對Javascript知識的匱乏和四棟讓我感覺很迷茫,上網查了一些資料,弄出來了哈。。。

 

直接進主題:

建立一個日期對象:

var objDate=new Date([arguments list]);

 

參數形式有以下5種:
new Date("month dd,yyyy hh:mm:ss");<br />new Date("month dd,yyyy");<br />new Date(yyyy,mth,dd,hh,mm,ss);<br />new Date(yyyy,mth,dd);<br />new Date(ms);

說明:

month:用英文表示月份名稱,從January到December
mth:用整數表示月份,從0(1月)到11(12月)

Content


dd:表示一個月中的第幾天,從1到31
yyyy:四位元表示的年份
hh:小時數,從0(午夜)到23(晚11點)
mm:分鐘數,從0到59的整數
ss:秒數,從0到59的整數
ms:毫秒數,為大於等於0的整數,表示的是需要建立的時間和GMT時間1970年1月1日之間相差的毫秒數。

 

我發現了:

Javascript中日期的構造還可以支援 new Date("yyyy/MM/dd"); 其中:MM是整數表示月份從0(1月)到11(12月),這樣再利用Regex就很方便地能夠轉換字串日期了。

 

測試代碼:

<mce:script type="text/javascript"><!--<br />document.write("<br/>" + new Date("February 3,2009"));<br />document.write("<br/>" + new Date("February 3,2009 10:52:03"));<br />document.write("<br/>");<br />document.write("<br/>" + new Date(2009,1,3));<br />document.write("<br/>" + new Date(2009,1,3,10,52,03));<br />document.write("<br/>");<br />document.write("<br/>" + new Date(Date.parse("February 3,2009")));<br />document.write("<br/>" + new Date(Date.parse("February 3,2009 10:52:03")));<br />document.write("<br/>" + new Date(Date.parse(2009,1,3)));//Output: NAN<br />document.write("<br/>" + new Date(Date.parse(2009,1,3,10,52,03)));//Output: NAN<br />document.write("<br/>" + new Date(Date.parse("2009/02/03")));<br />document.write("<br/>");<br />document.write("<br/>" + new Date("2009/02/03"));<br />document.write("<br/>" + new Date("2009/02/03 11:12:13"));<br />document.write("<br/>" + new Date("2009-02-03"));//Output: NAN</p><p>// --></mce:script>

輸出結果:

Tue Feb 3 00:00:00 UTC+0800 2009
Tue Feb 3 10:52:03 UTC+0800 2009

Tue Feb 3 00:00:00 UTC+0800 2009
Tue Feb 3 10:52:03 UTC+0800 2009

Tue Feb 3 00:00:00 UTC+0800 2009
Tue Feb 3 10:52:03 UTC+0800 2009
NaN
NaN
Tue Feb 3 00:00:00 UTC+0800 2009

Tue Feb 3 00:00:00 UTC+0800 2009
Tue Feb 3 11:12:13 UTC+0800 2009
NaN 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.