vb.net 计算两个日期之间的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8688242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating time between two dates?
提问by Meysam Savameri
Can someone please help me to make this work?
有人可以帮我完成这项工作吗?
I want to calculate the time between two dates in VB.NET like this:
我想像这样计算 VB.NET 中两个日期之间的时间:
startdate: 2011/12/30
enddate: 2011/12/31
Calculate: ? hour ? minute ? seconds
计算: ?小时 ?分钟 ?秒
回答by 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:
而 VB.Net 相当于上面的:
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)
回答by Daniel A. White
When you subtract 2 DateTime
s, you get a TimeSpan
struct that has all of those properties for you.
当您减去 2DateTime
秒时,您会得到一个TimeSpan
包含所有这些属性的结构体。
回答by Jason
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.:
基于这个问题,计算两个日期之间的时间,最好使用DateDiff。在下面的示例中,我们还可以将小时替换为分钟、秒、月等:
Dim timeDif As Long = DateDiff(DateInterval.Hour, startDate, endDate)
Using TimeSpan returns the time difference excluded the daily cycle, see below code:
使用 TimeSpan 返回排除每日周期的时差,见下面的代码:
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