Calculate time difference and return only hours and minutes (in VB.net)

此生再无相见时 提交于 2019-12-19 04:13:03

问题


I'm developing a system to calculate time difference. How can I compare two time (with date) and get the hours & minutes of the difference?

Example 1:

datetime1 = 1-Apr-2014 01:05:04 AM
datetime2 = 1-Apr-2014 02:05:04 AM

Results will be:

datetime2 - datetime1 = 01 Hours 00 Minutes

Example 2:

datetime1 = 1-Apr-2014 01:05:04 AM
datetime2 = 2-Apr-2014 02:15:04 AM

Results will be:

datetime2 - datetime1 = 25 Hours 10 Minutes

A negative value (for datetime1 > datetime2) would also be helpful for indicating that datetime1 is greater than datetime2

Example:

datetime1 = 2-Apr-2014 01:05:04 AM
datetime2 = 1-Apr-2014 01:05:04 AM

Results will be:

datetime2 - datetime1 = -24 Hours 00 Minutes

Thank you!


回答1:


My recommendation would be to use something like

Dim minutesDiff = DateDiff(DateInterval.Minute,datetime1,datetime2)
Console.WriteLine("{0} hours {1} minutes", Math.Abs(minutesDiff) / 60, Math.Abs(minutesDiff) Mod 60)

To extend this to seconds:

Dim secondsDiff = DateDiff(DateInterval.Second,datetime1,datetime2)
Console.WriteLine("{0} hours {1} minutes {2} seconds", Math.Abs(secondsDiff)/3600, (Math.Abs(secondsDiff) Mod 3600) / 60, Math.Abs(secondsDiff) Mod 60)



回答2:


Another way, you can use TotalHours and Minutes property of TimeSpan object resulted from subtracting two DateTimes :

Dim d1 As DateTime = DateTime.Now
Dim d2 As DateTime = DateTime.Now.AddHours(25).AddMinutes(10)

Dim difference As TimeSpan = d2 - d1
'round down total hours to integer'
Dim hours = Math.Floor(difference.TotalHours)
Dim minutes = difference.Minutes
'Following line prints : 25 Hours 10 Minutes'
Console.WriteLine("{0} Hours {1} Minutes", hours, minutes)



回答3:


Solutions to my question is:

Dim d1 As DateTime = DateTime.Parse("1-Apr-2014 10:10:00 AM")
Dim d2 As DateTime = DateTime.Parse("2-Apr-2014 10:10:00 AM")
Dim difference As TimeSpan = d2 - d1
'round down total hours to integer'
Dim hours = Math.Floor(difference.TotalHours)
Dim minutes = Math.Abs(difference.Minutes)
Dim seconds = difference.Seconds
Dim timeleft As String = Format(hours, "00") + " h " + Format(minutes, "00") + " m " + Format(seconds, "00") + " s "
If Int(seconds) < 0 Then
     timeleft = "00 h 00 m 00 s (Time Out)"
End If
Return timeleft 
' timeleft 24 hours 00 minutes 00 seconds


来源:https://stackoverflow.com/questions/22879310/calculate-time-difference-and-return-only-hours-and-minutes-in-vb-net

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