I have the string "9:00 AM". I would like to get the offset from midnight as a TimeSpan in C#?
views:
83answers:
4
+4
A:
9:00 AM
is a punctual time, while TimeSpan structure represents time intervals so you are trying to convert apples to oranges.
Darin Dimitrov
2009-10-10 13:29:50
+1 Your answer was absolutely correct with respect to the original question, but based on the OPs comments I've updated the question to reflect what he really wants.
tvanfosson
2009-10-10 13:42:02
A:
Timespan? A timespan is just a period of time. The "AM" shows that this is a specific time, so this cannot be a timespan. Or do you want to parse "9:00", without the "AM", and get a timespan of 9 hours as result?
@Your comment:
You could use a method that does this for you. Here's a simple example implementation (you would need to add better input validation, use better convert methods than just Convert.ToInt32() and so on):
public static TimeSpan GetTimeSpanFormString(string strString)
{
strString = strString.Trim();
string[] strParts = strString.Split(':', ' ');
int intHours, intMinutes;
if (strParts.Length != 3)
throw new ArgumentException("The string is not a valid timespan");
intHours = strParts[2].ToUpper() == "PM" ? Convert.ToInt32(strParts[0]) + 12 : Convert.ToInt32(strParts[0]);
intMinutes = Convert.ToInt32(strParts[1]);
return new TimeSpan(intHours, intMinutes, 0);
}
Maximilian Mayerl
2009-10-10 13:31:48
+2
A:
If you want the offset from midnight, you can use:
DateTime dateTime = DateTime.ParseExact( strValue, "h:mm tt" );
TimeSpan offset = dateTime - DateTime.Today;
tvanfosson
2009-10-10 13:36:39