Thursday, March 29, 2012

C# Converting PT0H0M0S to TimeSpan


I was working on importing Microsoft Project data into one of my projects when I encountered a problem where the MSP's TimePhasedData value is using the format PT0H0M0S to represent date values. I needed to convert the PT0H0M0S string to a double representing the total hours. I'm posting this code just in case someone is looking for something similar.

public static double StringToTimeSpan(string source)
   int hours = 0; int minutes = 0; int seconds =0;
   string number = string.Empty ;
   for (int index = 0; index < source.Length; index++) {
      char current = source[index];

      if ("1234567890".Contains(current)) number += current;

      else
{
         if (current.Equals ('H')) hours += int.Parse(number);
         if (current.Equals ('M')) minutes += int.Parse(number);
         if (current.Equals ('S')) seconds += int.Parse(number);
         number = string.Empty ;
      }
   }
   return new TimeSpan (hours, minutes, seconds).TotalHours;

}

1 comment: