Click here to Skip to main content
15,909,651 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hi,
I have the following example 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>
Does exists a method in C# to do that?

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

Thx!
Cheers..
Alessandro
Posted

1 solution

What you call "normal time" is not time at all! This is just a string presentation of time. The time itself is represented by System.DataTime and does not have any certain format. Time is time, there is not 24-hour time or 12-hour time, and the calendar itself is culture-independent.

By the way, your 12-hour format you show in your example shows indefinite time, because it also needs AM/PM specifiers. Also, calling it "normal" is ridiculous. In many cultures people will perceive it like quite abnormal. Don't try to claim your habits have universal value. :-)

So, to solve your problem look at the method System.DataTime.ToString and various format specifiers for time. This method name is overloaded, so there are several method. You could use the one with the parameter of format provider and use the instance of the class System.Globalization.CultureInfo as IFormatProvider. You can always use low-level format string.

See the code sample with format provider here: http://msdn.microsoft.com/en-us/library/ht77y576.aspx[^].
See the help on these classes:
http://msdn.microsoft.com/en-us/library/system.datetime.aspx[^], http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx[^].

—SA
 
Share this answer
 
v2
Comments
alessandro.campagna 31-May-11 13:10pm    
Another user gived me the solution and I share it for everyone has my same problem:

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"));

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900