Calculating time between two dates?
Asked Answered
B

3

9

Can someone please help me to make this work?

I want to calculate the time between two dates in VB.NET like this:

startdate: 2011/12/30  
enddate: 2011/12/31  

Calculate: ? hour ? minute ? seconds

Bodleian answered 31/12, 2011 at 13:4 Comment(0)
H
23

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

And the VB.Net equivalent to the above:

Dim startTime As DateTime = DateTime.Now

Dim endTime As DateTime = DateTime.Now.AddSeconds(75)

Dim span As TimeSpan = 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)
Housman answered 31/12, 2011 at 13:28 Comment(3)
For anyone using this, keep in mind that span.Seconds will NOT return the total time difference in seconds, but rather the difference in the seconds components (up to 59 max). To return the total difference, use span.TotalSeconds, span.TotalMinutes, etc.Assuan
@cybermonkey something like this is your friend...Forspent
@JamieBarker Yes, but the OP specifically stated they wanted VB.NET code. Some users on here will try and copy + paste the code thinking it'll work.Calvary
N
5

When you subtract 2 DateTimes, you get a TimeSpan struct that has all of those properties for you.

Niehaus answered 31/12, 2011 at 13:5 Comment(0)
M
3

Based on the question, calculating the time between two dates, it is better to use DateDiff. On below example, we can also replace the Hour with Minute, Second, Month, etc.:

Dim timeDif As Long = DateDiff(DateInterval.Hour, startDate, endDate)

Using TimeSpan returns the time difference excluded the daily cycle, see below code:

Dim startDate As Date = Date.Now
Dim endDate As Date = startDate.AddDays(3)  'add 3 days to startDate
Dim timeSpan As TimeSpan = endDate.Subtract(startDate)
Dim difDays As Integer = timeSpan.Days   'get 3 days
Dim difHr As Integer = timeSpan.Hours    'get 0 hours although 3 days difference
Dim difMin As Integer = timeSpan.Minutes 'get 0 minutes although 3 days difference
Misti answered 23/1, 2013 at 19:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.