在2个文本框中找到日期和时间之间的时差,然后将答案放在第三个文本框中. [英] Find the difference between the date and time in 2 text boxes and place the answer in a third.
问题描述
我有一个按钮,用于将当前日期和时间(现在)放置在文本框中.稍后按下时,另一个按钮会将当前日期和时间放置在另一个文本框中.
我希望单击另一个按钮时,第三个文本框中显示两个日期和时间之间的差异.
我该怎么办?
谢谢
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
推荐答案
好吧,Abhinav发送的代码编写得不好,而且显然没有经过他的测试.他写道:
Well, the code that Abhinav sent is not well-written, and obviously not tested by him. He wrote:
TimeSpan dt = Convert.ToDateTime(text1.text) - Convert.ToDateTime(text2.text);
textbox3.text = "Days " + dtDiff.Days.ToString() +
"Hours " + dtDiff.TotalHours() +
"Minutes " + dtDiff.TotalMinutes();
首先,我假设text2应该在text1之后,因此您实际上想从text1减去text2,但是我确定您已经弄清楚了.
其次,他声明了一个名为"dt"的TimeSpan
,然后引用了"dtDiff".
第三,为了显示小时数,他使用了TotalHours()
.
您真正想要的是我刚刚测试的
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
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"
(它在VB中是因为您没有指定使用的语言,并且我已经在VB中设置了可以测试它的表单.
(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.
感谢帮助William.效果很好!
Thanks for the help William. That worked great!
在按钮的click事件上,您需要添加如下代码-
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();
这篇关于在2个文本框中找到日期和时间之间的时差,然后将答案放在第三个文本框中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!