Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert TimeSpan with Days > 0 to DateTime

Status
Not open for further replies.

ralphtrent

Programmer
Jun 2, 2003
958
US
Hi All,
I am generating a TimeSpan where the total days exceeds 0,
i.e. 1.12:15:45. I need to convert this to a DateTime type but when i do I get an error saying "String was not recognized as a valid DateTime." This is because of the number of Days. Any idea around this? I have tried to alter the timespan to add, in this case, 24 hours to the 12 hours in hopes it would return 36:15:45, but that did not work, i still returns 1.12:15:45. The only other way i can think of doing this is to monkey around with the string and create a new DateTime as follows:
Code:
System.Text.RegularExpressions.Regex lrxMatchAppServerDuration = 
  new System.Text.RegularExpressions.Regex("[0-9]+\\.[0-9]{2}:[0-9]{2}:[0-9]{2}");
int liAdditionalHours = 0;
try
{
 if (lrxMatchAppServerDuration.Match(lstrAppServerDuration).Success)
  {
   int liIndexOfDays = lstrAppServerDuration.IndexOf(".");
   int liTotalDays = Convert.ToInt32(lstrAppServerDuration.Substring(0, liIndexOfDays + 1).Replace(".", ""));
   lstrAppServerDuration = lstrAppServerDuration.Substring(liIndexOfDays);
   liAdditionalHours = liTotalDays * 24;
  }
 }
catch { throw; }
finally{lrxMatchAppServerDuration = null;}
TimeSpan ltsEngineDuration = (TimeSpan)Convert.ToDateTime(lstrAppServerDuration).AddHours(liAdditionalHours).TimeOfDay;

But this is a pain in the butt.

Any idea's?

Thanks,
RalphTrent
 
converting a timespan to a datatime requires a point in time. lets say that is DateTime.Now.
Code:
TimeSpan timespan = GetTimeSpan();
DateTime future = DateTime.Now.Add(timespan);


Jason Meckley
Programmer
Specialty Bakers, Inc.
 
I found the problem. I am saving the value that I want to convert in a datatable, I never told the table what type of data will be in this column. Once I did that, I was able to successfully do what I needed.

Thanks
RalphTrent
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top