날짜 및 시간 계산

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, getDategetFullYear 메서드를 사용하여 날짜 부분을 가져왔습니다. 이에 해당하는 set 메서드 그룹을 사용하면 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일로 올바르게 설정됩니다. 다음 예제에서는 현재 날짜에 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월 넷째 목요일로 정의되는 추수 감사절의 날짜를 확인합니다. 이 스크립트에서는 현재 연도의 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일 자정을 0일 0시로 보고 그 이후 경과된 시간을 밀리초 단위로 반환합니다. 날짜가 이 날짜 이전이면 getTime은 음수를 반환합니다.

getTime을 사용하여 경과된 시간을 계산하는 데 필요한 시작 시간과 종료 시간을 설정할 수 있습니다. 그러면 몇 초 정도의 짧은 시간이나 며칠에 달하는 긴 시간을 측정할 때 사용할 수 있습니다.

경과된 시간(초) 확인

이 예제는 경과된 시간을 초 단위로 계산하며 간격 길이에 관계없이 작동합니다. getTime 메서드를 사용하여 보고되는 밀리초는 0일부터 시작하는 절대값입니다. 따라서 이 값은 분, 시간, 일로 단위를 바꾸면서 계속 증가합니다.

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

참고 항목

개념

데이터 형식 요약