Parse TimeSpan 1:00 and 01:00

Viewed 121

i want to Parse a String of Hours for Example: 16:40, 01:00, 12:00, 1:00, 4:90

my Parsing way :

txtManDezStunden.Text = TimeSpan.ParseExact(txtManStunden.Text, "hh':'mm", null).TotalHours.ToString("0.00");

Everything works fine if the Input of txtManStunden.Text is 01:00 It "fails" when the Input is 1:00 which is a behavior i would like to catch.

Is there a way to still parse even if the Operator uses "01:00, 001:00, 1:00" as an input

Thanks for any recommendations

2 Answers

There's a couple of things you can do, but it depends on whether you expect the hours component can be the total number of hours in the time span (e.g. the TimeSpan.TotalHours property) and you could get an input of 123:00 to parse. Assuming that's not the case, then you can use the overload of TimeSpan.ParseExact that takes multiple format strings, for example:

var input = "001:00";
var formats = new [] { "h':'mm", "'0'h':'mm" };
var timeSpan = TimeSpan.ParseExact(input, formats, null);

However, if you do need to parse 123:00, then you will need to manually parse the string. Fortunately that is fairly simple to do by splitting the string up.

var input = "001:00";
var parts = input.Split(':');  
var hours = int.Parse(parts[0]);
var minutes = int.Parse(parts[1]);
var timeSpan = new TimeSpan(hours, minutes, 0);

Solution from @phuzi worked

I now use multiple Formats which it tries to Parse now works like a Charm.

TimeSpan.ParseExact(txtManStunden.Text, new[] { "hh':'mm", "hhh':'mm", "h':'mm", "h", "hh" }, null).TotalHours.ToString("0.00");

I cant Parse Hours Greater than 24 now, any way to fix it withouth breaking the current formating?

Related