แก้ไข

แชร์ผ่าน


How to: Obtain a TimeZoneInfo object

The most common way to obtain a TimeZoneInfo object is to retrieve information about it from the registry. To obtain the object, call the static (Shared in Visual Basic) TimeZoneInfo.FindSystemTimeZoneById method, which looks in the registry. Handle any exceptions thrown by the method, particularly the TimeZoneNotFoundException that's thrown if the time zone isn't defined in the registry.

Note

Starting in .NET 8, TimeZoneInfo.FindSystemTimeZoneById returns a cached TimeZoneInfo object instead of instantiating a new object. For more information, see FindSystemTimeZoneById doesn't return new object.

Example

The following code retrieves a TimeZoneInfo object that represents the Eastern Standard Time zone and displays the Eastern Standard time that corresponds to the local time.

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

The TimeZoneInfo.FindSystemTimeZoneById method's single parameter is the identifier of the time zone that you want to retrieve, which corresponds to the object's TimeZoneInfo.Id property. The time zone identifier is a key field that uniquely identifies the time zone. While most keys are relatively short, the time zone identifier is comparatively long. In most cases, its value corresponds to the StandardName property of a TimeZoneInfo object, which is used to provide the name of the time zone's standard time. However, there are exceptions. The best way to make sure that you supply a valid identifier is to enumerate the time zones available on your system and note the identifiers of the time zones present on them. For an illustration, see How to: Enumerate time zones present on a computer. The Finding the time zones defined on a local system article also contains a list of selected time-zone identifiers.

If the time zone is found, the method returns its TimeZoneInfo object. If the time zone is not found, the method throws a TimeZoneNotFoundException. If the time zone is found but its data is corrupted or incomplete, the method throws an InvalidTimeZoneException.

If your application relies on a time zone that must be present, you should first call the FindSystemTimeZoneById method to retrieve the time zone information from the registry. If the method call fails, your exception handler should then either create a new instance of the time zone or re-create it by deserializing a serialized TimeZoneInfo object. See How to: Restore time zones from an embedded resource for an example.

See also