Display the local time and GMT in C#

[local time]

This example uses a Timer to execute the following code every half second.

// Update the clocks.
private void tmrClock_Tick(object sender, EventArgs e)
    // Display the local time.
    DateTime now = DateTime.Now;
    lblLocalTime.Text = now.ToLongTimeString();
    lblLocalDate.Text = now.ToShortDateString();

    // Display the GMT time.
    DateTimeOffset local_offset = new DateTimeOffset(now);
    DateTimeOffset utc_offset = local_offset.ToUniversalTime();
    lblGmtTime.Text = utc_offset.DateTime.ToLongTimeString();
    lblGmtDate.Text = utc_offset.DateTime.ToShortDateString();

The code first uses DateTime.Now to get the current date and time. It uses the ToLongTimeString and ToShortDateString methods to display the local time and date.

Next the code converts the local time into a DateTimeOffset. This structure represents a time and date relative to UTC (which is basically the same as GMT). It then calls the structure’s ToUniversalTime method to convert the DateTimeOffset value to UTC. The code finishes by getting the DateTimeOffset structure’s DateTime and then displaying its long time and short date values.

Note that the ToLongTimeString, ToShortTimeString, ToLongDateString, and ToShortDateString methods are locale-aware so they return values with the format appropriate for the computer. For example, in the United States a short date would be displayed as in 1/20/16 and in Germany it would be displayed as 20.1.16.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in internationalization, system and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

3 Responses to Display the local time and GMT in C#

  1. Reg Hammond says:

    …but supposing the Local time is wrong? Any offsets based on it will also be wrong …

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.