Tarasov Tarasov - 1 month ago 5
ASP.NET (C#) Question

How I can get the difference by time?

i want to calculate a checktime to the time now and get the hours.

I have a string "time" for example...

string t1 = UserParam[12].ToString(); // "9/26"
string t2 = UserParam[13].ToString(); // "14:51\r"

I need them in my Project where I get from the License Server the time from a user and I want to show the difference to now. I want show this in hours.

I want a time how ---> 1 hour(s), 49 minute(s)


I assume t1 is the month and date and t2 is the hour and minute.

You can use DateTime.ParseExact:

string t1 = "9/26";
string t2 = "14:51";
DateTime dt = DateTime.ParseExact(string.Format("{0} {1}", t1, t2), "M/dd HH:mm", CultureInfo.InvariantCulture);
TimeSpan diff = DateTime.Now - dt;
double totalHours = diff.TotalHours;  // 0.726172292194444


I get a error --> not the right format

Maybe because you have unwanted characters at the end of the string(s) as in "14:51\r". You can use Trim or TrimEnd to remove them. For example:

string t2 = UserParam[13].ToString().TrimEnd(new []{ '\r', '\n' }); // 14:51