【问题标题】:Calculating date difference with timespan and future dates计算时间跨度和未来日期的日期差异
【发布时间】:2010-11-12 20:08:46
【问题描述】:

我正在尝试根据日期列按以下顺序标记网格中的行

  • 从今天起 2 天或更长时间 然后是红色
  • 当 1 天大时为黄色
  • 当 0 天时为绿色
  • 当日期在未来时 蓝色

我有以下工作正常,除了未来的日期是绿色而不是蓝色。

 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

【问题讨论】:

  • 天数将返回 0,除非您在未来至少 24 小时?因此,如果它是 2010/08/15 12:30:00 并且您的未来日期是 2010/08/16 0:30:00 那么我相信 TimeSpan 是 -00:12:00:00 等等?
  • 我试过 CASE
  • 可能......如果是这样的话,只需将 .Date 添加到 myDate 分配和 Select Case 中即可。
  • @Saif,“一天前”是指“前一天”还是“24 小时以上”?

标签: vb.net datetime datediff


【解决方案1】:

.Days 总是给出一个整数值,因此它在您至少 24 小时后才会起作用。您可以按照自己的建议解决它,也可以立即处理时间跨度差异。

您可能还需要考虑这种差异的含义。 2 天前是否意味着您要选择 48 小时前创建的元素,还是意味着例如在 11 月 10 日创建的所有条目。

【讨论】:

  • +1 用于识别 Days 的问题;如 cmets 中所述,寻求“小时”
【解决方案2】:

我可能会建议另一种编写代码的方法:

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

正如我在最初的 cmets 中所述,除非您在未来至少 24 小时,否则 Days 将返回 0。因此,如果它是 2010/08/15 12:30:00,而您的未来日期是 2010/08/16 0:30:00,那么 TimeSpan 为 -00:12:00:00 等,而 Days 将为 0。

【讨论】:

  • 我只在数据库中按日期。你的更优雅。
【解决方案3】:

我找到了解决办法。

我首先使用 Date.Compare 用 IF 包装我的 CASE 以首先检查日期是否在未来。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    相关资源
    最近更新 更多