Share via


日付と時刻の計算

日付の操作および比較、経過時間の計算など、カレンダーと時計に関する一般的なタスクを実行するには、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);

日付の加算と減算

前の例では、getMonthgetDate、および getFullYear の各メソッドを使用して日付の各部分を取得しました。 これと同等の一連の set メソッドを使用して、Date オブジェクトの値を変更できます。

次の例は、日付を前日の日付に設定する方法を示しています。 当日の日付および月の日にちを取得し、setDate メソッドを使用して日付を 1 日前に設定します。

// 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 日に正しく設定されます。 次の例では、現在の日付に 1 週間を加算します。 また、日付から時刻をクリアします。

var myDate : Date = new Date();
myDate.setDate(myDate.getDate() + 7);

// Clear the time.
myDate.setHours(0, 0, 0, 0);

月と年の操作

次の例には、現在の日付を使用して 1 月から始まる日付を出力するループが含まれています。 月は次の年に正しくインクリメントされます。

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);
}

次の例では、現在の日付の 1 年前の日付を取得します。

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;
}

次の例では、現在の月の最後の日を調べます。 これを行うには、次の月の最初の日を判別し、1 日を減算します。

// 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 の値を返します。 日曜日は 0、月曜日は 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);

次の例では、米国の 祝日である感謝祭の日付を調べます。感謝祭は、11 月の第 4 木曜日として定義されています。 このスクリプトは、現在の年の 11 月 1 日を検索し、最初の木曜日を検索した後で、3 週間を加算します。

// 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 日午前 00:00:00) から経過したミリ秒数を返します。 それより前の日付に対しては、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 日午前 00:00:00 と Date オブジェクトに格納されている時刻値との差をミリ秒単位で返します。 これにより、2 つの日付のミリ秒表現を比較できます。

しかし、ミリ秒ベースの日付比較は、いずれかの Date オブジェクトに午前 0 時以外の時刻が格納されている場合には正しく機能しません。

コンストラクターの引数を指定せずに Date オブジェクトを作成する場合、日付に関連付けられる時刻は現在の時刻です。 特定の日付に対して Date オブジェクトを作成する場合、日付に関連付けられる時刻はその日の開始時刻である午前 0 時です。

次の例では、現在の日付が指定された日付と同じであるかどうかを調べます。 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");
}

参照

概念

データ型の概要