2012-09-18 44 views
3

我正在編寫一些數據分析軟件,我想升級原始數據的時基。我的原始數據有2分鐘的時間步長。我想按5分鐘,每小時,每天和每月的時間步長將數據縮放到多個數據庫表中。我計劃從原始數據中運行這些數據以保持精確度。如何將Vb.net中的DateTime舍入爲最接近的5分

我目前遇到的問題是取初始值並找到最接近的'圓'時間點,我想要它,成爲我的起點。例如,我將從13/03/12 00:01:36開始,作爲我的起點,我希望代碼將13/03/12 00:00:00作爲最接近的時間點,以便開始計算從那裏。對於每一個時間點,我都希望在每一方面佔用一半的時間。所以12/03/12 23:57:30到13/03/12 00:02:29將變成13/03/12 00:00:00。

使用SQL查詢從Access獲取數據,並將Date和Value存儲在兩個並排數組中。以下是我的代碼到目前爲止。它將數值四捨五入到下一個5分鐘,而不是上升或下降到最近的5分鐘。

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 

感謝您的幫助

回答

8

讓我們嘗試一些VB,對於 「輪最近的5分鐘」 功能:

' 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 
1

一種可能是以下幾點:

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); 

這是C#代碼,我相信你能翻譯它。

+0

第一個數據點可能不在12/03/12 23:57:30,數據將來自幾個不同的記錄站點,在不同的站點啓動和停止倍。起點必須從數組中取出,因此循環尋找「最小值」。代碼中的註釋也表示「四捨五入到前五分鐘」,我希望代碼四捨五入到最接近的五分鐘。 – Pezzzz

+0

@Pezzzz:請簡單地嘗試一下。如果您只看到第一條評論,則沒有閱讀整個代碼。 '12/03/12 23:57:30'將四捨五入到12/03/13 00:00:00。沒有必要使用陣列中的任何內容,因爲您只需要四捨五入到最近的五分鐘。 –

+0

@Blam,當我第一次查看代碼時,它與現在是不同的,有3行以var,註釋和if語句開頭。他在編輯中改變了它。 – Pezzzz

1

你能怎麼辦? (非常基本,但它應該給出一個想法)

Dim tValue As Date = ScaleDate(0) 

'find the next highest 5 minute mark 
For RecordCounter = 0 To ScaleDate.GetLength(0)    
    If tValue > ScaleDate(RecordCounter) Then     
     tValue = ScaleDate(RecordCounter)    
    End If   
Next 

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

'compare the original value to the next highest. If more than 2.5 minutes, then subtract 5 minutes 
If DateDiff(DateInterval.Second, tValue, MinValue) > 150 Then 
    MinValue = tValue.AddMinutes(-5) 
Else 
    MinValue = tValue 
End If 
相關問題