Calculating time between two dates?

Deadly 提交于 2019-12-04 03:53:34
Manoj Savalia

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)

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!