DIV CSS 佈局教程網

JavaScript日期時間函數大全與Date物件詳解
編輯:JavaScript基礎知識     

以下是整理歸納的JavaScript日期函數大全,涵蓋常見操作,供大家參考查閱。

1.取得當前時間
復制代碼 代碼如下:var date=new Date();

2.年月日轉為日期型資料

復制代碼 代碼如下:
var applyDate = document.domainExceptionForm.applyDate.value;
applyDate = applyDate.split("T")[0];
var applyYear = applyDate.split("-")[0];
var applyMonth = applyDate.split("-")[1] - 1;
var applyDay = applyDate.split("-")[2];
var applyDate1 = new Date(applyYear, applyMonth, applyDay);

3.比較兩日期相差天數是否大於5

復制代碼 代碼如下:
parseInt((date-applyDate1) / (1000 * 60 * 60 * 24)) >= 5

4.比較兩個時間

復制代碼 代碼如下:
if (date.valueOf() > applyDate1.valueOf()) {
  alert("輸入日期不得小於當前日期!");
} else {
  alert("OK!");
}

5.取得當前時間的時分秒

復制代碼 代碼如下:
var tody = new Date();
var nian = tody.getFullYear();
var yue = tody.getMonth() + 1;
var day = tody.getDate();
var hour = tody.getHours();
var min = tody.getMinutes();
var miao = tody.getSeconds();

6.時間相加(固定日期35天後)

復制代碼 代碼如下:
var d = new Date("2006,7,12");
d.setDate(d.getDate() + 35);

7.Date物件的方法速查

Date 物件能讓你取得相對於 UTC 或本地系統的時間與日期。使用前必須先建立 Date 物件的實體,且方法多為非靜態、需應用於指定實例。常用方法如下:

復制代碼 代碼如下:getDate|取得當前日期(本月幾號)
getDay|取得今天是星期幾(0=周日)
getFullYear|取得當前年份(四位)
getHours|取得當前小時(0-23)
getMilliseconds|取得當前毫秒
getMinutes|取得當前分鐘
getMonth|取得當前月份(從0開始)
getSeconds|取得當前秒數
getTime|取得自1970.1.1以來的毫秒數
getTimezoneOffset|取得與UTC的偏移(分鐘)
getUTCDate / getUTCDay / getUTCFullYear / getUTCHours / getUTCMinutes / getUTCMonth / getUTCSeconds|取得UTC格式各項
getYear|取得縮寫年份(年份減1900)
setDate / setFullYear / setHours / setMinutes / setMonth / setSeconds / setTime|設定各項
toString|轉為日期時間字串
Date.UTC|回傳指定UTC日期的固定時間值

8.建立新的 Date 物件

語法:

復制代碼 代碼如下:
new Date();
new Date(year [, month [, date [, hour [, minute [, second [, millisecond ]]]]]] );

參數:year 為整數(0-99對應1900-1999,或四位數指定年份);month 為 0-11;date 為 1-31;hour 為 0-23;minute、second 為 0-59;millisecond 為 0-999,後續參數皆為可選。

例子:

復制代碼 代碼如下:
now = new Date(); //獲得當前日期時間
national_day = new Date (49, 10, 1); //建立指定日期
myDate = new Date();
dateTextField = (myDate.getMonth() + "/" + myDate.getDate() + "/" + myDate.getFullYear());

透過靈活組合這些 getter 與 setter,就能完成絕大多數日期計算與格式化需求。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved