TimeZone Example
This page was last reviewed on Oct 11, 2023.
Dot Net Perls
TimeZone. Day and night come in different phases across the planet. We have time zones so that no one needs to wake up at midnight local time.
With TimeZone.CurrentTimeZone, we can access the current time zone information on the system. This depends on the system's configuration. We can also use conversions based on the time zone.
An example. Here we get the current time zone with TimeZone.CurrentTimeZone, a shared property in VB.NET. We see the computer is located in the Pacific Standard Time zone.
Note StandardName is the name of the current time zone (here it is Pacific Standard Time, PST).
Note 2 The DaylightName is the Daylight Changes time zone name—so we know more about when the time changes each year.
Module Module1 Sub Main() Dim zone As TimeZone = TimeZone.CurrentTimeZone ' Get standard and daylight names. Dim standard As String = zone.StandardName Dim daylight As String = zone.DaylightName Console.WriteLine("STANDARD NAME: " + standard) Console.WriteLine("DAYLIGHT NAME: " + daylight) ' Get local and universal time for DateTime.Now. Dim local As DateTime = zone.ToLocalTime(DateTime.Now) Dim universal As DateTime = zone.ToUniversalTime(DateTime.Now) Console.WriteLine("LOCAL TIME: " + local) Console.WriteLine("UNIVERSAL TIME: " + universal) End Sub End Module
STANDARD NAME: Pacific Standard Time DAYLIGHT NAME: Pacific Daylight Time LOCAL TIME: 7/7/2018 7:11:49 AM UNIVERSAL TIME: 7/7/2018 2:11:49 PM
Notes, ToLocalTime. We call ToLocalTime to convert a DateTime into the local time zone. In this program, the local time was the same as DateTime.Now, as Now returned a local time.
Notes, ToUniversalTime. This takes a DateTime and converts it to a universal time—one that is not based on local time. A new DateTime is returned.
Summary. Daylight changes, and time zones, are a complex subject. But with the TimeZone.CurrentTimeZone property in VB.NET we gain insight into how dates and times are affected.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 11, 2023 (edit).
© 2007-2024 Sam Allen.