问题
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
回答1:
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)
回答2:
When you subtract 2 DateTime
s, you get a TimeSpan
struct that has all of those properties for you.
回答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
来源:https://stackoverflow.com/questions/8688242/calculating-time-between-two-dates