Manvaril
Manvaril

Reputation: 160

Get timezone offset and display C#

I need to get the current timezone offset of the machine my program is running on and display it in a textbox or label.

This is the code I have

var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

Upvotes: 0

Views: 7042

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241778

The code you posted for obtaining the offset is correct:

var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

Equally valid would be:

var offset = DateTimeOffset.Now.Offset;

The result of either of these is the current local offset, expressed as a TimeSpan. The only part you're missing is how to format it as a string for display. Though there are several options, I recommend a value such as "+05:30" or "-08:00".

string sign = offset < TimeSpan.Zero ? "-" : "+";
string output = sign + offset.ToString(@"hh\:mm");

You can then assign the output string to your label value.

Just for fun, if you'd like to explore how to do the same task with Noda Time, you could write this instead:

Instant now = SystemClock.Instance.Now;
DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault();
ZonedDateTime local = now.InZone(tz);
Offset offset = local.Offset;
string output = offset.ToString("m", CultureInfo.InvariantCulture);

Upvotes: 3

YourTextBoxName.Text = offset.TotalHours.ToString();

Upvotes: 0

Related Questions