将2次之间的差异转换为毫秒?
我有两个屏蔽的 TextBox 控件,想知道如何获取每个控件中的时间,然后将差异转换为毫秒。比如,在 tb1 中我写“12:01”,在 tb2 中我写“12:02”,然后单击一个按钮。单击该按钮后,它会启动计时器,并在 12:02 时显示一个消息框。除了时间转换部分之外,我知道如何完成所有这些工作。
如何才能实现呢?
I have two masked TextBox controls and was wondering how I'd go about getting the time in each one and then converting the difference into milliseconds. Like, say in tb1 I write "12:01" and in tb2 I write "12:02", and then click a button. Once the button's clicked it starts a timer and at 12:02 a messagebox will be displayed. I know how to do all of it except for the time conversion part.
How can it be achieved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
回答标题问题:
您可以使用它来设置计时器:
处理刻度时不要忘记禁用计时器。
但如果您希望在 12:03 举办活动,只需将
d1
替换为 DateTime.Now 即可。但目前还不清楚textBox1和textBox2的具体功能是什么。
To answer the title-question:
You can use this to set a Timer:
Don't forget to disable the timer when handling the tick.
But if you want an event at 12:03, just substitute DateTime.Now for
d1
.But it is not clear what the exact function of textBox1 and textBox2 are.
您必须将文本框的值转换为 DateTime (t1,t2),然后:
或使用 DateTime.TryParse(textbox1, out t1);
错误处理由您决定。
You have to convert textbox's values to DateTime (t1,t2), then:
Or use DateTime.TryParse(textbox1, out t1);
Error handling is up to you.
上述许多解决方案可能适合不同的人。
我想建议一个比“MusiGenesis”最接受的解决方案稍作修改的代码。
注意事项:
-
earlierTime.Subtract(laterTime)
你会得到一个负值。- 如果您需要整数值而不是双精度值,请使用
int milDiff = (int)DateTime.Now.Subtract(StartTime).TotalMilliseconds;
- 相同的代码可用于获取两个日期值之间的差异,您可能会得到
.TotalDays
或.TotalHours
而不是.TotalMilliseconds
Many of the above mentioned solutions might suite different people.
I would like to suggest a slightly modified code than most accepted solution by "MusiGenesis".
Considerations:
-
earlierTime.Subtract(laterTime)
you will get a negative value.- use
int milDiff = (int)DateTime.Now.Subtract(StartTime).TotalMilliseconds;
if you need integer value instead of double- Same code can be used to get difference between two Date values and you may get
.TotalDays
or.TotalHours
insteaf of.TotalMilliseconds
如果您只处理时间而不处理日期,您将只想处理 TimeSpan 并处理跨越午夜的情况。
If you are only dealing with Times and no dates you will want to only deal with TimeSpan and handle crossing over midnight.
请尝试以下操作:
Try the following:
如果您只想在 12:02 显示消息框,请使用延迟为 250 毫秒的计时器控件,该控件会不断检查当前时间是否为 12:02。如果是,则显示消息并停止计时器。请注意,这不需要开始时间字段(尽管您可能将其用于其他用途 - 我不知道 - 在这种情况下,此处提供给您的其他代码将会有所帮助)。
If you just want to display a message box at 12:02, use a timer control with delay of, say, 250ms, that keeps checking if the current time is 12:02. When it is, display the message and stop the timer. Note this does not require a start time field (although you may be using that for something else -- I don't know -- in which case the other code provided to you here will be helpful).
尝试:
Try:
VB.net,桌面应用程序。如果您需要以毫秒为单位的经过时间:
VB.net, Desktop application. If you need lapsed time in milliseconds: