JScript Date 物件
更新:2007 年 11 月
JScript Date 物件可以用來表示任意日期和時間、取得目前的系統日期,以及在不同日期之間換算。它有數個預先定義的屬性 (Property) 和方法。Date 物件可以儲存星期幾和年月日等日期,以及小時數、分鐘數、秒鐘數和毫秒數等時間。這項資訊是以 1970 年 1 月 1 日 00:00:00.000 Coordinated Universal Time (UTC) (正式名稱是格林威治中央時間,Greenwich Mean Time) 後的毫秒數為基礎。JScript 可以處理約 250,000 B.C. 到 255,000 A.D. 間的日期,但部分格式功能只支援 0 A.D. 到 9999 A.D. 間的日期。
建立 Date 物件
若要建立新的 Date 物件,請使用 new 運算子。以下範例會計算出今年已經過去的天數和剩餘的天數。
// Get the current date and read the year.
var today : Date = new Date();
// The getYear method should not be used. Always use getFullYear.
var thisYear : int = today.getFullYear();
// Create two new dates, one for January first of the current year,
// and one for January first of next year. The months are numbered
// starting with zero.
var firstOfYear : Date = new Date(thisYear,0,1);
var firstOfNextYear : Date = new Date(thisYear+1,0,1);
// Calculate the time difference (in milliseconds) and
// convert the differnce to days.
const millisecondsToDays = 1/(1000*60*60*24);
var daysPast : double = (today - firstOfYear)*millisecondsToDays;
var daysToGo : double = (firstOfNextYear - today)*millisecondsToDays;
// Display the information.
print("Today is: "+today+".");
print("Days since first of the year: "+Math.floor(daysPast));
print("Days until the end of the year: "+Math.ceil(daysToGo));
這個程式的輸出內容大致如下:
Today is: Sun Apr 1 09:00:00 PDT 2001.
Days since first of the year: 90
Days until the end of the year: 275