views:

83

answers:

4

I have the string "9:00 AM". I would like to get the offset from midnight as a TimeSpan in C#?

A: 
TimeSpan.TryParse(yourString, out yourTimeSpan);
HeavyWave
+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
+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
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
yes. I need to get 09:00:00 as result whwn i pass 09:00 AM. Another example, 16:00:00 as result when i pass 4:00 PM
Prasad
the above function worked for me. thanks.
Prasad
+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