다음을 통해 공유


방법: TimeZoneInfo 개체 인스턴스화

업데이트: 2007년 11월

TimeZoneInfo 개체를 인스턴스화하는 가장 일반적인 방법은 레지스트리에서 이 개체에 대한 정보를 검색하는 것입니다. 이 항목에서는 로컬 시스템 레지스트리에서 TimeZoneInfo 개체를 인스턴스화하는 방법에 대해 설명합니다.

TimeZoneInfo 개체를 인스턴스화하려면

  1. TimeZoneInfo 개체를 선언합니다.

  2. static(Visual Basic의 경우 Shared) TimeZoneInfo.FindSystemTimeZoneById 메서드를 호출합니다.

  3. 메서드에서 throw하는 예외 특히, 표준 시간대가 레지스트리에 정의되어 있지 않은 경우 throw되는 TimeZoneNotFoundException을 처리합니다.

예제

다음 코드에서는 동부 표준 시간대를 나타내는 TimeZoneInfo 개체를 검색하여 현지 시간에 해당하는 동부 표준시를 표시합니다.

Dim timeNow As Date = Date.Now
Try
   Dim easternZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
   Dim easternTimeNow As Date = TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, easternZone)
   Console.WriteLine("{0} {1} corresponds to {2} {3}.", _
                     timeNow, _
                     IIf(TimeZoneInfo.Local.IsDaylightSavingTime(timeNow), _
                         TimeZoneInfo.Local.DaylightName, TimeZoneInfo.Local.StandardName), _
                     easternTimeNow, _
                     IIf(easternZone.IsDaylightSavingTime(easternTimeNow), _
                         easternZone.DaylightName, easternZone.StandardName))
' Handle exception
'
' As an alternative to simply displaying an error message, an alternate Eastern
' Standard Time TimeZoneInfo object could be instantiated here either by restoring
' it from a serialized string or by providing the necessary data to the
' CreateCustomTimeZone method.
Catch e As TimeZoneNotFoundException
   Console.WriteLine("The Eastern Standard Time Zone cannot be found on the local system.")
Catch e As InvalidTimeZoneException
   Console.WriteLine("The Eastern Standard Time Zone contains invalid or missing data.")   
Catch e As SecurityException
   Console.WriteLine("The application lacks permission to read time zone information from the registry.")
Catch e As OutOfMemoryException
   Console.WriteLine("Not enough memory is available to load information on the Eastern Standard Time zone.")
' If we weren't passing FindSystemTimeZoneById a literal string, we also 
' would handle an ArgumentNullException.
End Try
DateTime timeNow = DateTime.Now;
try
{
   TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
   DateTime easternTimeNow = TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, 
                                                   easternZone);
   Console.WriteLine("{0} {1} corresponds to {2} {3}.",
                     timeNow, 
                     TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ?
                               TimeZoneInfo.Local.DaylightName : 
                               TimeZoneInfo.Local.StandardName,
                     easternTimeNow, 
                     easternZone.IsDaylightSavingTime(easternTimeNow) ?
                                 easternZone.DaylightName : 
                                 easternZone.StandardName);
}
// Handle exception
//
// As an alternative to simply displaying an error message, an alternate Eastern
// Standard Time TimeZoneInfo object could be instantiated here either by restoring
// it from a serialized string or by providing the necessary data to the
// CreateCustomTimeZone method.
catch (TimeZoneNotFoundException)
{
   Console.WriteLine("The Eastern Standard Time Zone cannot be found on the local system.");
}  
catch (InvalidTimeZoneException)
{
   Console.WriteLine("The Eastern Standard Time Zone contains invalid or missing data.");
}
catch (SecurityException)
{
   Console.WriteLine("The application lacks permission to read time zone information from the registry.");
}
catch (OutOfMemoryException)
{
   Console.WriteLine("Not enough memory is available to load information on the Eastern Standard Time zone.");
}
// If we weren't passing FindSystemTimeZoneById a literal string, we also 
// would handle an ArgumentNullException.

TimeZoneInfo.FindSystemTimeZoneById 메서드의 단일 매개 변수는 검색할 표준 시간대의 식별자이며 개체의 TimeZoneInfo.Id 속성에 해당합니다. 표준 시간대 식별자는 표준 시간대를 고유하게 식별하는 키 필드입니다. 대부분의 키가 비교적 짧은 데 반해 표준 시간대 식별자는 상당히 깁니다. 대부분의 경우 이 식별자의 값은 표준 시간대 표준 시간의 이름을 지정하는 데 사용되는 TimeZoneInfo 개체의 StandardName 속성에 해당합니다. 그러나 여기에는 예외가 있습니다. 올바른 식별자를 지정하는 가장 좋은 방법은 시스템에서 사용 가능한 표준 시간대를 열거하고 해당 표준 시간대의 식별자를 적어 두는 것입니다. 자세한 내용은 방법: 컴퓨터에 있는 표준 시간대 열거를 참조하십시오. 로컬 시스템에 정의된 표준 시간대 찾기 항목에도 선택된 표준 시간대의 목록이 포함되어 있습니다.

표준 시간대를 찾으면 이 메서드는 해당 표준 시간대의 TimeZoneInfo 개체를 반환합니다. 표준 시간대를 찾지 못하면 이 메서드는 TimeZoneNotFoundException을 throw합니다. 표준 시간대를 찾았지만 해당 데이터가 손상되어 있거나 완전하지 않은 경우 이 메서드는 InvalidTimeZoneException을 throw합니다.

응용 프로그램에서 반드시 있어야 하는 표준 시간대를 사용하는 경우에는 먼저 FindSystemTimeZoneById 메서드를 호출하여 레지스트리에서 해당 표준 시간대 정보를 검색해야 합니다. 메서드 호출에 실패하는 경우에는 예외 처리기에서 표준 시간대의 새 인스턴스를 만들거나 serialize된 TimeZoneInfo 개체를 deserialize하여 다시 만들어야 합니다. 예제는 방법: 포함 리소스에서 표준 시간대 복원을 참조하십시오.

코드 컴파일

이 예제에는 다음 사항이 필요합니다.

  • System.Core.dll에 대한 참조를 프로젝트에 추가해야 합니다.

  • System 네임스페이스를 using 문을 사용하여 가져와야 합니다(C# 코드인 경우 필요).

참고 항목

작업

방법: 미리 정의된 UTC 및 현지 표준 시간대 개체에 액세스

개념

로컬 시스템에 정의된 표준 시간대 찾기

기타 리소스

시간 및 표준 시간대