JS基礎--Date

來源:互聯網
上載者:User

標籤:

一、Date類型

Date類型使用自UTC(Coordinated Universal Time,國際協調時間)1970年1月1日午夜起至改日期止經過的毫秒數。

二、建立日期對象

  1. var date=new Date()——建立一個表示當地時區的目前時間的Date對象。
  2. var date=new Date("May 25,2004")——返回時間毫秒數,如果參數為數字,則返回當前數字表示毫秒數的時間。
  3. ECMAScript提供的兩個方法:(都是基於本地時區而非GTM)。
  • Date.parse()——接收表示時間的字串,返回相應日期毫秒數,如果傳入的字串不能表示日期,則返回NaN。
  • Date.UTC()——接收表示時間的字串,返回相應日期毫秒數,與Date.parse()不同的是其參數分別是年,月(0-11),日(1-31),小時數(0-23),分鐘秒以及毫秒數,其中 年和月是必須的。
  • Date.now()——返回表示調用這個方法的日期和時間的毫秒數。。
var date=new Date();console.log(date);// Date {Fri Aug 05 2016 15:17:27 GMT+0800}var date=new Date("2004/5/25");//在後台調用Date.parse()console.log(date);// Date {Tue May 25 2004 00:00:00 GMT+0800}var date=new Date(Date.parse("2004/5/25"));console.log(date);// Date {Tue May 25 2004 00:00:00 GMT+0800}console.log(Date.parse("2004/5/25"));//1085414400000var date=new Date(Date.UTC(2005,04,5,17,55,55));console.log(date);// Date {Fri May 06 2005 01:55:55 GMT+0800}var start=Date.now();for(var i=0;i<10;i++){}var stop=Date.now();result=stop-start;console.log(result);//1,for迴圈執行了1ms

三、繼承方法

  1. toLocaleString()——會按照與瀏覽器設定的地區相適應的格式返回日期和時間,可能包括AM,PM,但不會包含時區資訊(具體的格式因瀏覽器而異)。
  2. toString()——通常返回帶有時區資訊的日期和時間,時間一般以軍用時間(0-23)表示。
  3. valueOf()——不返回字串,而是返回日期的毫秒。利於時間比較。
var date1=new Date(2007,0,1);var date2=new Date(2007,1,1);console.log(date1<date2);//trueconsole.log(date1>date2);//false

四、日期格式化方法

  1. toDateString()——以特定於實現的格式顯示星期幾、月、日、年。
  2. toTimeString()——以特定於實現的格式顯示時、分、秒和時區。
  3. toLocaleDateString()——以特定於地區的格式顯示星期幾、月、日、年。
  4. toLocaleTimeString()——以特定於實現的格式顯示時、分、秒。
  5. toUTCString()——以特定於實現的格式完整的UTF格式。
var date=new Date();console.log(date.toDateString());//Sat Aug 06 2016console.log(date.toTimeString());//23:01:04 GMT+0800console.log(date.toLocaleDateString());//2016/8/6console.log(date.toLocaleTimeString());//下午11:01:04console.log(date.toUTCString());//Sat, 06 Aug 2016 15:01:04 GMT

六、日期/時間組件方法

常用的

  1. getTime()——返回表示日期的毫秒數,與valueOf()方法返回的值相同。
  2. setTime()——以毫秒數設定日期,會改變整個日期。
  3. getFullYear()——取得4位元的年份。
  4. getMonth()——返回日期中的月份,0-11。
  5. getUTCMonth()——返回UTC日期中的月份0-11。
  6. getDate()——返回日期月份中的天數1-31。
  7. getDay()——返回日期中星期的星期幾(0為周日,6為周六)。
  8. getHours()——返回日期中的小時數(0-23)。
  9. getMinutes()——返回日期中的分鐘數(0-59)。
  10. getSeconds()——返回日期中的秒數(0-59)。

JS基礎--Date

聯繫我們

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