Question

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)

Était-ce utile?

La solution

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

Edit:

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

Autres conseils

You'll want your times in DateTime structures. If you have timestamp information in a string, then you should use DateTime.TryParse to fill a DateTime. But if you have the timestamp in a string it will be important to specify time zone info in the style parameter (DateTimeStyles).

Then you can take make a TimeSpan by subtracting two DateTime stucts and use the TotalHours property

(dt1 - dt2).TotalHours

You can use DateTime.Subtract to calculate the difference between dates and times:

string date = "9/26 14:51";
DateTime dt = DateTime.ParseExact(date, "M/dd HH:mm", CultureInfo.InvariantCulture);
TimeSpan diff = DateTime.Now.Subtract(dt);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top