Berechnung Datum Differenz mit Zeitspanne und zukünftige Termine
Frage
Ich versuche, Flagge Zeilen in einem Raster in der folgenden Reihenfolge auf der Grundlage einer Datumsspalte
- Wenn 2 oder mehr Tage alt von heute dann rot
- Wenn 1 Tag alt dann GELB
- Wenn 0 Tage alt dann GRÜN
- Wenn das Datum in der Zukunft dann BLUE
Ich habe die folgende, die feine Arbeit ist bis auf die zukünftigen Termine, die GREEN sind statt blau.
Dim myDate As DateTime = CType(grdSummaryView.GetRowCellValue(e.RowHandle, "myDate"), DateTime)
Select Case Now.Subtract(myDate).Days
'2 or more days old then RED FLAG
Case Is >= 2
e.Value = ImageCollection2.Images(3)
Case 1
'1 day old then YELLOW FLAG
e.Value = ImageCollection2.Images(1)
Case 0
'Current day then GREEN FLAG
e.Value = ImageCollection2.Images(0)
Case Else
e.Value = ImageCollection2.Images(4)
End Select
Lösung
I might suggest an alternate way of writing the code:
Dim age As Double = Now.Substract(myDate).TotalDays
If age >= 2 Then
e.Value = ImageCollection2.Images(3) //Red
ElseIf age >= 1 Then
e.Value = ImageCollection2.Images(1) //Yellow
ElseIf age >= 0 Then
e.Value = ImageCollection2.Images(0) //Green
Else
e.Value = ImageCollection2.Images(4) //Blue
End If
As mentioned in my initial comments, Days will return 0 unless you are at least 24 hours in the future. So if it is 2010/08/15 12:30:00 and your future date is 2010/08/16 0:30:00 then the TimeSpan is -00:12:00:00 etc and Days will be 0.
Andere Tipps
The .Days always gives an Integer value so it won't work until you are at least 24 hours into the future. You can either solve it as you suggested yourself or work immediately with the Timespan difference.
You also might want to consider the meaning of this difference. Does 2 days old mean that you want to select elements that were created 48 hours ago or does it mean all entries made on the 10th of November for instance.
I found a solution.
I first wrap my CASE with a IF using Date.Compare to first check if the date is in the future.
If Date.Compare(myDate, Now) < 0 Then
Select Case Now.Subtract(delivDate).Days
Case Is >= 2
'2 or more days old then RED FLAG
e.Value = ImageCollection2.Images(3)
Case 1
'1 day old then YELLOW FLAG
e.Value = ImageCollection2.Images(1)
Case Else
'0 day (current day) then GREEN FLAG
e.Value = ImageCollection2.Images(0)
End Select
Else
'DATE IS IN THE FUTURE
e.Value = ImageCollection2.Images(4)
End If