Sorry if the title make you feel confusing because of my bad english. I have a ListBox which contain many items which have time format (For example: 00:02:22:33) I want to convert this time format into minutes
For example: 00:02:22:33 -> 02 hours = 120 minutes
33 seconds = 33/60 = 0.55 minutes
So result is 120+22+0.55 = 142.55
What i'm trying is writing a method like:
public static void Timeconvert(ListBox l)
{
foreach (var item in l.Items)
{
int x, int y, int z; //It just to show you my thought
if(item.format = 00:x:y:z)
{
int result = x*60 +y + z/60 ;
item = result.Tostring();
}
}
}
I'm new to C# so i explained as detail as i could, so please help me :(
Just parse the string as span of time and use TotalMinutes
property.
var time = TimeSpan.Parse("00:02:22:33");
var convertedToMinutes = time.TotalMinutes; //Returns 142.55
This will update your list items
for (int i = 0; i < listBox1.Items.Count; i++)
{
TimeSpan time = TimeSpan.Parse(listBox1.Items[i].ToString());
listBox1.Items[i] = time.TotalMinutes;
}
Alternately, TryParse()
can be used for handling strings in an incorrect format: if (TimeSpan.TryParse(listBox1.Items[i].ToString(), out time)) { listBox1.Items[i] = time.TotalMinutes; }
if (TimeSpan.TryParse(listBox1.Items[i].ToString(), out time)) { listBox1.Items[i] = time.TotalMinutes; }
You may try following:
var regex = new System.Text.RegularExpressions.Regex(@"00:\d{2}:\d{2}:\d{2}");
foreach (var item in l.Items)
{
if (regex.IsMatch(item))
{
item = TimeSpan.Parse(item).TotalMinutes.ToString();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.