Convert Difference between 2 times into Milliseconds?
Solution 1:
DateTime dt1 = DateTime.Parse(maskedTextBox1.Text);
DateTime dt2 = DateTime.Parse(maskedTextBox2.Text);
TimeSpan span = dt2 - dt1;
int ms = (int)span.TotalMilliseconds;
Solution 2:
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.
Solution 3:
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.
Solution 4:
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