Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 200
Meysam Savameri Avatar asked Dec 31 '11 13:12

Meysam Savameri


People also ask

Can you calculate the time between two dates?

To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months.

How do you calculate elapsed hours between two dates?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.


2 Answers

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)
like image 65
Manoj Savalia Avatar answered Oct 10 '22 17:10

Manoj Savalia


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

like image 32
Daniel A. White Avatar answered Oct 10 '22 17:10

Daniel A. White