방법: TimeZoneInfo 개체 가져오기

개체를 가져오는 TimeZoneInfo 가장 일반적인 방법은 레지스트리에서 개체에 대한 정보를 검색하는 것입니다. 개체를 가져오려면 레지스트리를 static 찾는 (Shared Visual Basic에서) TimeZoneInfo.FindSystemTimeZoneById 메서드를 호출합니다. 메서드에서 throw된 예외, 특히 TimeZoneNotFoundException 표준 시간대가 레지스트리에 정의되지 않은 경우 throw되는 예외를 처리합니다.

참고 항목

.NET 8 TimeZoneInfo.FindSystemTimeZoneById 부터 새 개체를 인스턴스화하는 대신 캐시된 TimeZoneInfo 개체를 반환합니다. 자세한 내용은 FindSystemTimeZoneById가 새 개체를 반환하지 않음을 참조 하세요.

예시

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

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.
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

TimeZoneInfo.FindSystemTimeZoneById 메서드의 단일 매개 변수는 개체의 TimeZoneInfo.Id 속성에 해당하는, 검색할 표준 시간대의 식별자입니다. 표준 시간대 식별자는 표준 시간대를 고유하게 식별하는 키 필드입니다. 대부분 키는 비교적 짧지만 표준 시간대 식별자는 비교적 깁니다. 대부분의 경우 해당 값은 표준 시간대의 표준 시간 이름을 제공하는 데 사용되는 StandardName 개체의 TimeZoneInfo 속성에 해당합니다. 그러나 예외 사항이 있습니다. 유효한 식별자를 제공하는지 확인하는 가장 좋은 방법은 시스템에서 사용 가능한 표준 시간대를 열거하고 표시된 표준 시간대의 식별자를 확인하는 것입니다. 자세한 내용은 How to: Enumerate time zones present on a computer를 참조하세요. 로컬 시스템 문서에 정의된 표준 시간대 찾기에는 선택한 표준 시간대 식별자 목록도 포함되어 있습니다.

표준 시간대가 있는 경우 메서드는 해당 TimeZoneInfo 개체를 반환합니다. 표준 시간대가 없는 경우 메서드에서 TimeZoneNotFoundException이 발생합니다. 표준 시간대가 있지만 해당 데이터가 손상되었거나 불완전한 경우 메서드에서 InvalidTimeZoneException이 발생합니다.

애플리케이션에서 사용하는 표준 시간대가 있어야 하는 경우 먼저 FindSystemTimeZoneById 메서드를 호출하여 레지스트리에서 표준 시간대 정보를 검색합니다. 메서드 호출이 실패하면 예외 처리기가 표준 시간대의 새 인스턴스를 만들거나 직렬화된 TimeZoneInfo 개체를 역직렬화하여 다시 만들어야 합니다. 예제는 방법: 포함된 리소스에서 표준 시간대 복원을 참조하세요.

참고 항목