日期及時間計算
使用 Date 物件和相關方法,可以執行通用日曆和時脈任務,如管理和比較日期,以及計算已耗用的時間。
將日期設定為目前日期。
建立 Date 物件的執行個體時,其包含代表特定時間的值 (精確到毫秒)。 您然後可以讀取或變更日期和時間值。
下列範例示範如何取得目前日期,並以格式 mm/dd/yy 顯示。
// Create a date object. Because no arguments are
// passed, the date object contains the current date and
// time (to the millisecond).
var dt : Date = new Date();
// Determine and display the month, day, and year.
// The getMonth method uses a zero offset for
// the month number.
var month : Number = dt.getMonth()+1;
var day : Number = dt.getDate();
var year : Number = dt.getFullYear();
print (month + "/" + day + "/" + year);
設定特定日期
下列範例中,特定日期會傳遞至建構函式。
// Create a date object for a specific date.
var dt : Date = new Date('8/24/2009');
JScript 對於日期格式具有高度彈性。 它允許各種變化形式,如 8-24-2009、August 24、2009 和 24 Aug 2009。
您還可以指定時間,如下列範例所示:
// Create a date object for a specific date and time.
// The time format is hours:minutes:seconds.
var dtA : Date = new Date('8/24/2009 14:52:10');
// Create a date object for the same date and time as in
// the previous example.
// The parameters are:
// year, month, day, hours, minutes, seconds.
// August is month 7 because January is month 0.
var dtB : Date = new Date(2009, 7, 24, 14, 52, 10);
加減天數
上述範例使用 getMonth、getDate 和 getFullYear 方法來取得日期的各部分。 使用一組相同的設定方法,您可以變更 Date 物件中的值。
下列範例說明如何將日期設定為前一天的日期。 它包含目前日期以及月份日期,然後使用 setDate 方法將日期設定為前一天的日期。
// Get the current day's date and day of month.
var myDate : Date = new Date();
var dayOfMonth : Number = myDate.getDate();
// Reset myDate to one day earlier.
myDate.setDate(dayOfMonth - 1);
JScript 按需要遞增到下個月或年。 例如,目前日期如果是 1 月 28 日,這時若增加 7 天,則日期會正確地設定為 2 月 4 日。 下列範列會將目前日期加上一個星期。 該範例也會清除日期中的時間。
var myDate : Date = new Date();
myDate.setDate(myDate.getDate() + 7);
// Clear the time.
myDate.setHours(0, 0, 0, 0);
使用月份和年份
下列範例包含的迴圈會從目前日期,以一個月開始輸出日期。 月份正確遞增到下一年。
var currentDate : Date = new Date();
for(var index : int = 1; index <= 12; index++)
{
var myDate : Date = new Date();
myDate.setMonth(currentDate.getMonth() + index);
print ("Month+" + index + ": " + myDate);
}
下列範列包含去年今天的日期。
var myDate : Date = new Date();
myDate.setFullYear (myDate.getFullYear() - 1);
下列範例包含下一月份第一天的日期。 該範例會遞增月份,然後將月份日期設定為 1。
function GetFirstOfNextMonth() : Date
{
var myDate : Date = new Date();
myDate.setMonth(myDate.getMonth() + 1);
myDate.setDate(1);
return myDate;
}
下列範例確定目前月份的最後一天。 為實現此功能,該範例會確定下一月份的第一天,然後再減一天。
// Determine the last day of the current month.
// The GetFirstOfNextMonth() function is in the previous example.
var myDate : Date = GetFirstOfNextMonth();
myDate.setDate (myDate.getDate() - 1);
使用星期
getDay 方法 (請勿與 getDate 混淆) 會傳回 0 到 6 之間的值來指示星期。 星期日為零,星期一為 1,以此類推。 下列範例顯示如何確定目前是星期幾。
var arDays : Array = ["Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"];
var today : Date = new Date();
var dayNum : Number = today.getDay();
var dayOfWeek : String = arDays[dayNum];
下列範列傳回上一個星期五的日期。
function getPreviousDayOfWeek(dayOfWeekNum : Number) : Date
{
var dt : Date = new Date();
if (dt.getDay() == dayOfWeekNum)
{
// It is currently the day of the week specified in
// the function call. Subtract one week.
dt.setDate(dt.getDate() - 7);
}
else
{
// Go back a day at a time until arriving
// at the specified day of week.
while (dt.getDay() != dayOfWeekNum)
{
dt.setDate(dt.getDate() - 1);
}
}
return dt;
}
var friday : Number = 5;
var myDate : Date = getPreviousDayOfWeek(friday);
下列範例確定 U.S 日期。 感恩節的日期為十一月第四個星期四。 指令碼先找到目前年份的 11 月 1 日,再找到第一個星期四,然後增加三個星期。
// Determine the current date and clear the time.
var myDate : Date = new Date();
myDate.setHours(0, 0, 0, 0);
// Determine November 1 of the current year.
var november : Number = 10;
myDate.setMonth(november);
myDate.setDate(1);
// Find Thursday.
var thursday : Number = 4;
while(myDate.getDay() != thursday)
{
myDate.setDate(myDate.getDate() + 1) ;
}
// Add 3 weeks.
myDate.setDate(myDate.getDate() + 21);
計算已耗用時間
getTime 方法會傳回從 1970 年 1 月 1 日午夜零時起已耗用的毫秒數。 getTime 會傳回負數表示此日期以前的日期。
可以使用 getTime 設定計算已耗用時間的開始和結束時間。 它可以用來測量小單位 (如秒數),也可以測量大單位 (如天數)。
以秒為單位確定已耗用時間
這個範例以秒為單位計算已耗用時間。 無論間隔時間長短,照常執行。 由 getTime 方法報告的毫秒數是從零日期開始計算的絕對值。 因此,分鐘、小時和天的變更會使毫秒數持續增加。
Console.Write("What is your name? ");
var startTime : Date = new Date();
var name : String = Console.ReadLine();
var endTime : Date = new Date();
var elapsed : Number =
(endTime.getTime() - startTime.getTime()) / 1000;
Console.WriteLine("You took " + elapsed +
" seconds to type your name.");
以天為單位確定已耗用時間
若要處理更多可管理的單位,可以用一個適當的數除以 getTime 方法提供的毫秒數。 例如,若要將毫秒數轉換為天數,應用 86,400,000 (1000 x 60 x 60 x 24) 除以毫秒數。
下列範例顯示從目前年份的第一天開始算起已耗用時間。 範例中使用連續的除法運算來計算以天、小時、分鐘和秒為單位的已耗用時間。 不計入日光節約時間。
// Set the unit values in milliseconds.
var msecPerMinute : Number = 1000 * 60;
var msecPerHour : Number = msecPerMinute * 60;
var msecPerDay : Number = msecPerHour * 24;
// Determine the current date and time.
var today : Date = new Date();
// Determine January 1, at midnight, of the current year.
var january : Number = 0;
var startOfYear : Date = new Date();
startOfYear.setMonth(january);
startOfYear.setDate(1);
startOfYear.setHours(0, 0, 0, 0);
// Determine the difference in milliseconds.
var interval : Number = today.getTime() - startOfYear.getTime();
// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
var days : Number = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );
// Calculate the hours, minutes, and seconds.
var hours : Number = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );
var minutes : Number = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );
var seconds : Number = Math.floor(interval / 1000 );
// Display the result.
var msg : String = days + " days, " + hours + " hours, "
+ minutes + " minutes, " + seconds + " seconds.";
print(msg);
確定使用者的年齡
下列範例決定以年為單位確定使用者的年齡。 從目前年份減去出生年份,如果目前年份的生日還未發生,則再減 1。 不使用已耗用的毫秒數,因為我們不根據嚴格的時間間隔來對年齡進行定義。
var birthday : Date = new Date("8/1/1985");
var today : Date = new Date();
var years : Number = today.getFullYear() - birthday.getFullYear();
// Reset birthday to the current year.
birthday.setFullYear(today.getFullYear());
// If the user's birthday has not occurred yet this year, subtract 1.
if (today < birthday)
{
years--;
}
print("You are " + years + " years old.");
![]() |
---|
比較日期時務必要小心,確定整個操作過程正確。 您可以透過下列主題,進一步了解相關內容。 |
下列範例會示範以月為單位計算使用者年齡的一種方法。 指令碼包含一個測試,判斷使用者的生日在目前年份中是否已經發生。
var birthday : Date = new Date("8/1/1985");
var today : Date = new Date();
var years : Number = today.getFullYear() - birthday.getFullYear();
// Determine the number of months.
var months : Number = (years * 12) +
(today.getMonth() - birthday.getMonth());
// Adjust the months if the birthday has not occurred
// yet in the current month.
if (today.getDate() < birthday.getDate())
{
months--;
}
print("You are " + months + " months old.");
比較日期
JScript 中,如果您使用大於或小於 (<、>、<= 或 >=) 來比較物件,則在進行比較之前,會先評估物件的值。 等於比較運作方式不同。 如果您使用 == 運算子,則只有在運算子的兩方參考同一物件的情況下,比較才會傳回 true。 != 運算子的操作相似。
getTime 方法會傳回 1970 年 1 月 1 日午夜零點和 Date 物件中時間值之間的毫秒數。 這樣,您可以比較兩個日期的毫秒表示值。
但是,如果一個 Date 物件包含非午夜零時的時間,則以毫秒為單位的日期比較無法正確執行。
如果您建立一個不包含建構函式引數的 Date 物件,則與日期關聯的時間為目前時間。 如果您建立一個針對特定日期的 Date 物件,則與日期關聯的時間為特定日期的午夜零時。
下列範例會檢查目前日期是否與指定日期一致。 為在 todayAtMidn 中設定目前日期,指令碼針對目前年、月和日建立一個 Date 物件。
// Determine the current date and time, and then
// determine the current date at midnight.
var now : Date = new Date();
var todayAtMidn : Date =
new Date(now.getFullYear(), now.getMonth(), now.getDate());
// Set specificDate to a specified date at midnight.
var specificDate : Date = new Date("9/21/2009");
// Compare the two dates by comparing the millisecond
// representations.
if (todayAtMidn.getTime() == specificDate.getTime())
{
print("Same");
}
else
{
print("Different");
}