Title: Display the local time and GMT in C#
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 the example to experiment with it and to see additional details.
|