0

I need to convert TimeZoneInfo.DisplayName to TimeZoneInfo.Id.

I am getting the DisplayName from a combobox populated from names taken from TimeZoneInfo.GetSystemTimeZones()

2 Answers2

0

Get like this

var timeZone = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(t => t.DisplayName == displayName).Id;
Mustafa Arslan
  • 774
  • 5
  • 13
0

Converting is not necessary, nor is it recommended.

TimeZoneInfo.GetSystemTimeZones() returns a collection of TimeZoneInfo objects, not strings.

When you assign that collection to a combo box (assuming a Windows.Forms.ComboBox per our discussion in the comments here), the combo box will show the DisplayName property of each TimeZoneInfo object, but the original object is retained.

All you really need is to get the Id of the TimeZoneInfo object that is selected by the combo box.

In other words, assuming you're populating the combobox like this:

this.cboTimeZone.DataSource = TimeZoneInfo.GetSystemTimeZones();

Then you can get the Id of the select item like this:

TimeZoneInfo tzi = (TimeZoneInfo) this.cboTimeZone.SelectedItem;
string id = tzi?.Id;

Or as a single statement:

string id = ((TimeZoneInfo) this.cboTimeZone.SelectedItem)?.Id;

Note that I use the ?. operator, so that the resulting string will be null if there is no item selected, rather than throwing a NullReferenceException.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Also - keep in mind that the strings of the `Id` property are intended to identify the time zone to the system. Those strings will be the same regardless of the language settings of Windows. The `DisplayName` string however, is intended to be human-readable, and will change to match the Windows language settings. – Matt Johnson-Pint Sep 08 '20 at 19:57