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

FOX 9000
  • 123
  • 1
  • 1
  • 6
Meysam Savameri
  • 558
  • 2
  • 12
  • 30

3 Answers3

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)
Jamie Barker
  • 8,145
  • 3
  • 29
  • 64
Manoj Savalia
  • 1,402
  • 3
  • 13
  • 36
  • 6
    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. – http203 Apr 01 '14 at 19:52
  • @cybermonkey something [like this](http://converter.telerik.com/) is your friend... – Jamie Barker Apr 14 '15 at 11:28
  • 1
    @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. – AStopher Apr 14 '15 at 17:14
5

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
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
Jason
  • 31
  • 1