Meysam  Savameri
Meysam Savameri

Reputation: 556

Calculating time between two dates?

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

Upvotes: 9

Views: 54324

Answers (3)

Manoj Savalia
Manoj Savalia

Reputation: 1402

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)

Upvotes: 23

Jason
Jason

Reputation: 31

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

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190897

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

Upvotes: 5

Related Questions