Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a button that places the current date and time (Now) in a text box. Another button places the current date and time in another text box when pressed later.

I would like the difference between the 2 dates and times to appear in a third text box when another button is clicked.

How do I do this?

Thank You
Posted
Updated 17-Mar-10 7:19am
v2

Well, the code that Abhinav sent is not well-written, and obviously not tested by him. He wrote:

C#
TimeSpan dt = Convert.ToDateTime(text1.text) - Convert.ToDateTime(text2.text);
textbox3.text = "Days  " + dtDiff.Days.ToString() +  
   "Hours " + dtDiff.TotalHours() + 
   "Minutes " + dtDiff.TotalMinutes();


First, I would assume that text2 should be after text1, so you would actually want to subtract text2 from text1, but I'm sure you figured that out.
Second, he declared a TimeSpan called "dt" and then referenced "dtDiff".
Third, to display hours, he used TotalHours(). TotalHours() will give you the difference between the two dates in only hours.
What you really want, and what I just tested would be

VB
Dim dtDiff As TimeSpan = Convert.ToDateTime(txtDate2.Text) - _
                         Convert.ToDateTime(txtDate1.Text)
txtDateDiff.Text = dtDiff.Days & " Days, " & dtDiff.Hours & _
                   " Hours, " & dtDiff.Minutes & " Minutes, " & _
                   dtDiff.Seconds & " Seconds"


(It's in VB because you didn't specify which language you were working in, and I had a form already set up in VB where I could test it.
 
Share this answer
 
Thanks for the help William. That worked great!
 
Share this answer
 
On a button's click event, you need to add code as follows -

TimeSpan dt = Convert.ToDateTime(text1.text) - Convert.ToDateTime(text2.text);
textbox3.text = "Days  " + dt.Days.ToString() +  
   "Hours " + dt.TotalHours() + 
   "Minutes " + dt.TotalMinutes();
 
Share this answer
 
v4
That doesnt seem to work. But thank you for responding anyway.
 
Share this answer
 
You are right, I should have mentioned what I was working with. I'm using Visual Studio 2008.
 
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