VB.NET
Public Shared Function RoundedHour(ByVal dt As DateTime) As DateTime Return DateTime.Parse( _ String.Format("{0:yyyy-MM-dd HH:00:00}", _ IIf(dt.Minute > 30, dt.AddHours(1), dt) _ ) End Function
C#
public static DateTime RoundedHour(ByVal dt As DateTime) { Return DateTime.Parse( String.Format("{0:yyyy-MM-dd HH:00:00}", (dt.Minute > 30 ? dt.AddHours(1) : dt) ) }
It's pretty straight forward. If the minutes of the time are over 30 then add an hour. If not, keep using the given date. Format the date to have the minutes and seconds set to 0 and parse it back as a date.
Thank you so much for this example (VB.NET) I was looking for a way to supply an SQL query for records between the last hour and this one.
ReplyDeleteI modified your function slightly, iif(dt.minute >= 0, dt.addhours(-1),dt) to get last hour.
Pleased it helped :)
ReplyDeleteused the basis of this to create function to round to next hour for a transaction count refresh point. Worked well!
ReplyDelete