I need to convert TimeZoneInfo.DisplayName
to TimeZoneInfo.Id
.
I am getting the DisplayName from a combobox populated from names taken from TimeZoneInfo.GetSystemTimeZones()
I need to convert TimeZoneInfo.DisplayName
to TimeZoneInfo.Id
.
I am getting the DisplayName from a combobox populated from names taken from TimeZoneInfo.GetSystemTimeZones()
Get like this
var timeZone = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(t => t.DisplayName == displayName).Id;
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
.