Solved

VB.net - calculate time difference

Posted on 2013-06-04
Medium Priority
519 Views
VB.net

Let say I have the two date/times:
6/4/2013 5:46:41 PM
6/4/2013 5:50:03 PM
=  3:22 seconds

6/4/2013 5:54:29 PM
6/4/2013 5:55:30 PM
= 0:59 seconds

How can I can calculate how many minutes and seconds between the two times?
0
Question by:keith1001

LVL 17

Expert Comment

ID: 39220814

If minutes = 0 then datrdiff s

HTH,

Kent
0

LVL 22

Assisted Solution

Thomasian earned 1000 total points
ID: 39220878
``````        Dim d1 As Date = Date.Parse("6/4/2013 5:46:41 PM")
Dim d2 As Date = Date.Parse("6/4/2013 6:50:03 PM")

Dim ts As TimeSpan = d2.Subtract(d1)

Dim s1 As String = ts.ToString  'hh:mm:ss
Dim s2 As String = String.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.Seconds.ToString("00")) 'mm:ss

MessageBox.Show(String.Format("{0}{1}{2}", s1, Environment.NewLine, s2))
``````
0

LVL 75

Accepted Solution

käµfm³d   👽 earned 1000 total points
ID: 39220879
Subtracting two dates in .NET yields a TimeSpan instance. You can interrogate the TotalSeconds property of that instance.

e.g.

``````Dim firstDate As DateTime = DateTime.Parse("6/4/2013 5:46:41 PM")
Dim secondDate As DateTime = DateTime.Parse("6/4/2013 5:50:03 PM")

Dim diff As TimeSpan = (secondDate - firstDate)

Console.WriteLine(diff.TotalSeconds)
``````
0

LVL 11

Expert Comment

ID: 39222002
hi.. you can try this

DateTime startTime = DateTime.Now;

DateTime endTime = DateTime.Now.AddSeconds( 75 );

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );

Output Like,

Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0
0

Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.