-2

Im writing a function to convert the time to the nearest half hour using Visual Studio 2010. Eg, 15:23 to 15:30 then if 15:05, it will convert to 15:00.

Anyone has ideas? Thanks in advance.

2 Answers2

2

You can use this method:

Public Enum eRoundingDirection
    up
    down
    nearest
End Enum

Public Shared Function RoundDateTime(dt As DateTime, minutes As Integer, direction As eRoundingDirection) As DateTime
    Dim t As TimeSpan
    Select Case direction
        Case eRoundingDirection.up
            t = (dt.Subtract(DateTime.MinValue)).Add(New TimeSpan(0, minutes, 0))
        Case eRoundingDirection.down
            t = (dt.Subtract(DateTime.MinValue))
        Case Else
            t = (dt.Subtract(DateTime.MinValue)).Add(New TimeSpan(0, minutes \ 2, 0))
    End Select

    Return DateTime.MinValue.Add(New TimeSpan(0, (CInt(t.TotalMinutes) \ minutes) * minutes, 0))
End Function

to round the current time to the nearest half-hour:

Dim rounded = RoundDateTime(Date.Now, 30, eRoundingDirection.nearest):

originally found(in C#) here

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Check out this answer how to round time It's a javascript example but the same should be possible with vb.net.

Community
  • 1
  • 1
faceman
  • 1,318
  • 11
  • 20