What is the best way to convert this string to minutes?

I have combobox in winforms that has the following elements:

15 min 30 min 1 hr 1 hr 30 min 2 hr 2 hr 30 min etc . . 

Here is a screenshot of the combobox winforms collection item editor

enter image description here

and I need to parse this line and return an integer that represents the number of minutes. I wanted to see the most elegant way to do this (right now I am dividing the space and then counting the length of the array, and this is a bit wrong.

So, parsing

 2h 30 mins 

will return 150

+4
source share
3 answers

Since you said it was a combo box, you have to analyze the value. The user can also enter his own value.

 var formats = new[] {"h' hr'", "m' min'", "h' hr 'm' min'"}; TimeSpan ts; if (!TimeSpan.TryParseExact(value, formats, null, out ts)) { // raise a validation message to your user. } // you said you wanted an integer number of minutes. var minutes = (int) ts.TotalMinutes; 

You can pass any string specified in your example as value .

However , remember that due to the way TimeSpan works, you cannot analyze more than 23 hours or more than 59 minutes with this approach. The program β€œ24 hours” or β€œ60 minutes” or any combination of these will not be performed.

+4
source

I would use Dictionary for this, so there was no parsing. (It works well when there is a fixed choice.) I am more familiar with Delphi UI controls than .NET, so there may be a better way to populate a ComboBox than what I'm doing here, but I'm sure someone will tell me if is, and I can fix it.

(The code is Oxygene, but it should be easily translatable in C # or VB.Net.)

 method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs); var KC: Dictionary<String, Int32>.KeyCollection; begin aItems := new Dictionary<String, Int32>; aItems.Add('15 min', 15); aItems.Add('30 min', 30); aItems.Add('1 hr', 60); aItems.Add('1 hr 30 min', 90); aItems.Add('2 hr', 120); aItems.Add('2 hr 30 min', 150); KC := aItems.Keys; for s in KC do comboBox2.Items.Add(s); comboBox2.DropDownStyle := ComboBoxStyle.DropDownList; end; method MainForm.comboBox2_SelectedIndexChanged(sender: System.Object; e: System.EventArgs); begin // Safe since style is DropDownList. label1.Text := aItems[comboBox2.SelectedItem.ToString].ToString(); end; 
0
source

This should work:

  static int GetAllNumbersFromString(string timeString) { int min = 0; MatchCollection mc=Regex.Matches(timeString, @"\d+"); if(timeString.Contains("hr") && mc.Count = 1) { min = mc[0] * 60; } else { if(mc.Count > 1) { min = mc[0] * 60 + mc[1]; } else { min = mc[0]; } } return min; } 
-1
source

Source: https://habr.com/ru/post/1488341/


All Articles