Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i face trouble when i try to calculate for example (11:00 PM to 1:00 AM)
i get the total of hours -21 instead of 2, so iam confused
this is my code:
C#
DateTime date1 =
    System.Convert.ToDateTime(DTimeBeginWork.Value);
DateTime date2 =
    System.Convert.ToDateTime(DTimeEndWork.Value);


TimeSpan ts = new TimeSpan();
ts = date2.Subtract(date1);
DgNHours.DigitText = (ts.Hours.ToString());
DgNMinutes.DigitText = (ts.Minutes.ToString());
Posted

It's much cleaner to use '-' operator naturally defined for System.DateTime, as in
C#
TimeSpan ts = date2 - date1;

This form would not leave a room for ambiguity in sign, but you can get either positive or negative time span, depending on what time is sooner.

And, for exact time interval (time span), use non-confusing TotalHours property, instead of Hours, or other Total* properties of System.TimeSpan:
http://msdn.microsoft.com/en-us/library/system.timespan.aspx[^].

—SA
 
Share this answer
 
Comments
Atif BOUZAGLAOUI 2-Jul-13 20:19pm    
whats the deferece between this :
TimeSpan ts = date2 - date1;
and this:
TimeSpan ts = new TimeSpan();
ts = date2.Subtract(date1);
i think the same and my problem is still exist
Sergey Alexandrovich Kryukov 3-Jul-13 0:35am    
I would agree. I only say: this is a correct code.

In other words, these two points in time really has the time span between them as it is calculated, no matter if you like it or not. It should be enough for you. If this is not what you want, check up other code, not the code in question.

—SA
C#
DateTime date1 = System.Convert.ToDateTime(DTimeBeginWork.Value);
DateTime date2 = System.Convert.ToDateTime(DTimeEndWork.Value);

string date1String = date1.ToString("dd-MM-yyyy hh:mm:ss tt"); 
string date2String = date2.ToString("dd-MM-yyyy hh:mm:ss tt");
 
TimeSpan ts = new TimeSpan();
ts = date2.Subtract(date1);
DgNHours.DigitText = (ts.TotalHours.ToString());
DgNMinutes.DigitText = (ts.Minutes.ToString());


In your code I added two statements for displaying date1 and date2 also changed the ts.Hours to ts.TotalHours. As per your example if you pass (11:00 PM to 1:00 AM) this code will return -22.
That is correct because if you check date1String and date2String it will be 03-07-2013 11:00:00 PM
and 03-07-2013 01:00:00 AM respectively ( as per today's date), the difference between these date will be -22.

If you pass the values as 03-07-2013 11:00:00 PM to 04-07-2013 01:00:00 AM then it will return 2 as result.So you have to pass the date along with the time value to get the proper result.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900