Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Round DateTime in Vb.net to the nearest 5mins

I am writing some data analysis software, I want to upscale timebase of my Raw Data. My Raw Data has a time step of ~2minutes. I want to scale the data into several database tables with a timestep of 5minutes, hourly, daily and monthly. I plan to run each of these from the raw data to keep my accuracy up.

The problem I am currently having is taking an initial value and finding the closest 'round' time point I want to it, to be my start point. For example, I will start with the point 13/03/12 00:01:36 as my start point, I want the code to find 13/03/12 00:00:00 as the closest time point so it will start calculating from there. For each time point I want to take half of the time step on each side. So 12/03/12 23:57:30 to 13/03/12 00:02:29 will become 13/03/12 00:00:00.

The Data is taken from Access using a SQL query and the Date and Value are stored in two side by side Arrays. Below is my code so far. It will round the values up to the NEXT 5 minutes, rather than up or down to the NEAREST 5 mimutes.

Private Sub RateStateScale(ByVal Parameter As Integer, ByVal Timebase As String)

    Dim NewDate(0)
    Dim NewData(0)
    Dim RecordCounter
    Dim MinValue As Date = ScaleDate(0)
    Dim startpoint As String

    For RecordCounter = 0 To ScaleDate.GetLength(0)
        If MinValue > ScaleDate(RecordCounter) Then
            MinValue = ScaleDate(RecordCounter)
        End If
    Next

    Do Until MinValue.Minute Mod 5 = 0
        MinValue = MinValue.AddMinutes(1)
    Loop



End Sub

Thanks for your help

like image 622
Pezzzz Avatar asked Dec 15 '22 19:12

Pezzzz


2 Answers

Let's try some VB, for a "round to nearest 5 minutes" function:

' just some date, should be a parameter to your function
Dim mydatetime = new DateTime(2012,3,12,23,57,30)

' split into date + time parts
Dim datepart = mydatetime.Date
Dim timepart = mydatetime.TimeOfDay

' round time to the nearest 5 minutes
timepart = TimeSpan.FromMinutes(Math.Floor((timepart.TotalMinutes+2.5)/5.0) * 5.0)

' combine the parts
Dim newtime = datepart.Add(timepart)
' a function would return this value
like image 86
Hans Kesting Avatar answered Dec 28 '22 22:12

Hans Kesting


One possibility would be the following:

var date = new DateTime(2012,03,12,23,57,30);
var fullFiveMinutes = date.Minute / 5;
// result will be our date rounded down to the previous full five minutes
var result = new DateTime(date.Year, date.Month, date.Day
                          date.Hour, fullFiveMinutes * 5, 0);

// if we add exactly 2.5 minutes to our date variable and the result represents
// another full five minutes we need to round up.
if(date.AddSeconds(2.5 * 60).Minute / 5 != fullFiveMinutes)
    result = result.AddMinutes(5);

This is C# code, I am sure you can translate it.

like image 24
Daniel Hilgarth Avatar answered Dec 29 '22 00:12

Daniel Hilgarth