Convert Difference between 2 times into Milliseconds?

后端 未结 11 2159
梦毁少年i
梦毁少年i 2020-12-06 09:11

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

相关标签:
11条回答
  • 2020-12-06 09:39

    VB.net, Desktop application. If you need lapsed time in milliseconds:

    Dim starts As Integer = My.Computer.Clock.TickCount
    Dim ends As Integer = My.Computer.Clock.TickCount
    Dim lapsed As Integer = ends - starts
    
    0 讨论(0)
  • 2020-12-06 09:42

    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.

    0 讨论(0)
  • 2020-12-06 09:42

    Try the following:

       DateTime dtStart;
       DateTime dtEnd;
    
       if (DateTime.TryParse( tb1.Text, out dtStart ) && DateTime.TryParse(tb2.Text, out dtEnd ))
       {
          TimeSpan ts = dtStart - dtEnd;
          double difference = ts.TotalMilliseconds;
       }
    
    0 讨论(0)
  • 2020-12-06 09:44
    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;
    
    0 讨论(0)
  • 2020-12-06 09:45

    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.

    0 讨论(0)
提交回复
热议问题