开发者

Convert string time to normal time value replacing the hour to the correct

I开发者_如何学Python have the following example string values:

24:05 , 25:08 , 26:59

and I need a function or something else to get a correct time value (hh:mm) like:

00:05 , 01:08 , 02:59

Is there a method in C# that does this?

Please help me, I gonna to be crazy on this!!

Thx! Cheers.. Alessandro


With regex you can do it like this:

var match = Regex.Match("25:05", @"^(\d{2,}):(\d{2})$");
var hour = int.Parse(match.Groups[1].Value) % 24;
var min = int.Parse(match.Groups[2].Value);

// hour will be 1 and min 5

If you like to avoid regular expressions then a simple input.IndexOf() and input.SubString() will do it.

Update: If you want a method for it, then take a look at this:

static TimeSpan ParseHHMM(string input)
{
    var match = Regex.Match(input, @"^(\d{2,}):(\d{2})$");
    var hour = int.Parse(match.Groups[1].Value) % 24;
    var min = int.Parse(match.Groups[2].Value);

    return new TimeSpan(hour, min, 0);
}

// Write to console
Console.WriteLine(ParseHHMM("25:05").ToString(@"hh\:mm"));

Update: I've changed \d{2} to \d{2,} for the hour part. This means it now can take an input like 125:05.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜