我正在尝试计算“时间前”,但我的代码中出现了差异。
使用今天的日期
2010 年 11 月 7 日
如果我使用2010 年 9 月 1 日,那么我的 .NET 代码和 JS 代码都说“2 个月”
如果我使用2010 年 8 月 31 日,那么我的 .NET 代码会显示“3 个月”,而我的 JS 代码会显示“2 个月”
这种差异一直持续到2010 年8 月 9 日。
基本上 dateDiff 从 8 月 10 日到 8 月 31 日“关闭”,基于今天 11 月 7 日的日期。
这是 JavaScript(取自“ timeago ”插件)
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 48 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.floor(days)) ||
days < 60 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.floor(days / 30)) ||
years < 2 && substitute($l.year, 1) ||
substitute($l.years, Math.floor(years));
这是我的 .NET 代码(由我编写)
Public Function ToDuration(ByVal dt As Date?, _
Optional ByVal suffixAgo As String = Nothing) As String
If Not dt Is Nothing Then
Dim theDate As Date = dt
Dim SecondsAppart As Integer = DateDiff(DateInterval.Second, theDate, Now)
Dim output As String
If SecondsAppart < 86400 Then
Select Case SecondsAppart
Case Is <= 59 : output = "less than a minute " & suffixAgo
Case Is <= 119 : output = "about a minute " & suffixAgo
Case Is <= 3599 : output = DateDiff(DateInterval.Minute, theDate, Now) & " minutes " & suffixAgo
Case Is <= 7199 : output = "about an hour " & suffixAgo
Case Else : output = DateDiff(DateInterval.Hour, theDate, Now) & " hours " & suffixAgo
End Select
Else
Dim DaysAppart As Integer = DateDiff(DateInterval.Day, theDate, Now)
Select Case DaysAppart
Case Is <= 1 : output = "yesterday"
Case Is <= 30 : output = DateDiff(DateInterval.Day, theDate, Now) & " days " & suffixAgo
Case Is <= 60 : output = "about a month " & suffixAgo
Case Is <= 365 : output = DateDiff(DateInterval.Month, theDate, Now) & " months " & suffixAgo
Case Is <= 730 : output = "about a year " & suffixAgo
Case Else : output = DateDiff(DateInterval.Year, theDate, Now) & " years " & suffixAgo
End Select
End If
Return output
Else
Return String.Empty
End If
End Function
因此,我遇到的问题既是基本问题,也是后勤问题。
- 当涉及到 DateDiff 时,哪个代码是“正确的”?(IE:2个月零14天算2个月还是3天?)
- 让他们相应地排队的最佳方法是什么?