Click here to Skip to main content
15,879,348 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i need to calculate between two times from pm to am
i did this code but i face problem from pm to am because it's another day,
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 = ((int)(ts.Hours)).ToString();
			DgNHours.DigitText = (ts.Hours.ToString());
			DgNMinutes.DigitText = (ts.Minutes.ToString());



thank u
Posted
Comments
Sergey Alexandrovich Kryukov 30-Jun-13 23:02pm    
It looks like you question lacks on word: calculate what between two times? Duration, or what? What's the role of AM/PM? What's the problem?

Do you understand that it cannot make any difference: this is a matter of time formatting, not the time structure itself.
—SA
Atif BOUZAGLAOUI 30-Jun-13 23:12pm    
i need to calculate hours and minutes; also when from pm to am it means the time will enter other day , so i cant enter and show me minus

Hi !

TimeSpan t = date1 - date2;

with t you can translate result to Hour, Minute, Seccond, day, month, year through properties same as type.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-Jul-13 0:58am    
Actually, date2 - date1. OP have actually done an equivalent operation, so it won't resolve the problem (even though using '-' operator is much more readable). I think the solution of the problem would be... coming to understanding that the problem does not really exist.
—SA
As long as you are working with DataTime you should be OK - so I guess your DTimeBeginWork contains only the time in some format and not the date?

That being the case, you either need to specify the date or assume the date is the next day if the endwork time value is less than the Beginwork time value...

e.g.

C#
if (DTimeBeginWork.Value > DTimeEndWork.Value)
{
    date2.AddDays(1);
}
 
Share this answer
 
Comments
Atif BOUZAGLAOUI 30-Jun-13 23:18pm    
i need to calculate hours and minutes; also when from pm to am it means the time will enter other day , so when it enter and it show minus and it be back
Atif BOUZAGLAOUI 30-Jun-13 23:18pm    
i tried yyour code but nothing change
Bhaiyasaheb 15002513 30-Dec-20 1:47am    
its work for me thank you i make some changes and it work for me..

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