Calculate time difference and return only hours an

2020-03-04 09:10发布

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!

3条回答
ゆ 、 Hurt°
2楼-- · 2020-03-04 09:18

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
查看更多
\"骚年 ilove
3楼-- · 2020-03-04 09:21

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)
查看更多
男人必须洒脱
4楼-- · 2020-03-04 09:37

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)
查看更多
登录 后发表回答