How can I get the offset as a TimeSpan if I only have the time as a string, such as 09:00 AM

StackOverflow https://stackoverflow.com/questions/1547933

  •  20-09-2019
  •  | 
  •  

Question

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

Was it helpful?

Solution

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

OTHER TIPS

9:00 AM is a punctual time, while TimeSpan structure represents time intervals so you are trying to convert apples to oranges.

If you want the offset from midnight, you can use:

  DateTime dateTime = DateTime.ParseExact( strValue, "h:mm tt" );
  TimeSpan offset = dateTime - DateTime.Today;
TimeSpan.TryParse(yourString, out yourTimeSpan);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top