Convert Difference between 2 times into Millisecon

2019-01-15 05:03发布

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?

11条回答
Luminary・发光体
2楼-- · 2019-01-15 05:40

You have to convert textbox's values to DateTime (t1,t2), then:

DateTime t1,t2;
t1 = DateTime.Parse(textbox1.Text);
t2 = DateTime.Parse(textbox2.Text);
int diff = ((TimeSpan)(t2 - t1)).TotalMilliseconds;

Or use DateTime.TryParse(textbox1, out t1); Error handling is up to you.

查看更多
相关推荐>>
3楼-- · 2019-01-15 05:44

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".

DateTime firstTime = DateTime.Parse( TextBox1.Text );
DateTime secondTime = DateTime.Parse( TextBox2.Text );
double milDiff = secondTime.Subtract(firstTime).TotalMilliseconds;

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

查看更多
叼着烟拽天下
4楼-- · 2019-01-15 05:51

If you are only dealing with Times and no dates you will want to only deal with TimeSpan and handle crossing over midnight.

TimeSpan time1 = ...;  // assume TimeOfDay
TimeSpan time2 = ...;  // assume TimeOfDay
TimeSpan diffTime = time2 - time1;
if (time2 < time1)  // crosses over midnight
    diffTime += TimeSpan.FromTicks(TimeSpan.TicksPerDay);
int totalMilliSeconds = (int)diffTime.TotalMilliseconds;
查看更多
Fickle 薄情
5楼-- · 2019-01-15 05:52
DateTime dt1 = DateTime.Parse(maskedTextBox1.Text);
DateTime dt2 = DateTime.Parse(maskedTextBox2.Text);
TimeSpan span = dt2 - dt1;
int ms = (int)span.TotalMilliseconds;
查看更多
成全新的幸福
6楼-- · 2019-01-15 05:52

To answer the title-question:

DateTime d1 = ...;
DateTime d2 = ...;
TimeSpan diff = d2 - d1;

int millisceonds = (int) diff.TotalMilliseconds;

You can use this to set a Timer:

timer1.interval = millisceonds;
timer1.Enabled = true;

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.

查看更多
够拽才男人
7楼-- · 2019-01-15 05:57
var firstTime = DateTime.Now;
var secondTime = DateTime.Now.AddMilliseconds(600);
var diff = secondTime.Subtract(firstTime).Milliseconds;


// var diff = DateTime.Now.AddMilliseconds(600).Subtract(DateTime.Now).Milliseconds;
查看更多
登录 后发表回答