我正在計算「timeago」,並且我想到了我的代碼中的一個缺陷。日期計算差異(JavaScript VS .NET)
用今天的日期
2010年11月7日
如果我使用2010年9月1日然後我的兩個.NET代碼和我的JS代碼說 「2個月」
如果我使用2010年8月31日然後我的.NET代碼說「3個月」,我的JS代碼說在「2個月」
此差異一直保留到2010年8月9日。
基本上DATEDIFF爲「關」,從8月10日 - 根據11月7日的當天的日期8月31日
這裏是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?)
- 什麼是最好的方法讓他們排隊呢?
我要做的一件事就是用<替換<=。你現在編碼的方式正在運行,你說的是兩個月還在一個月前。與730天相同大約一年。 – 2010-11-08 03:16:00
我想知道,如果選擇美國大部分時區的日期從標準時間到標準時間的變化,這是否是巧合。 – kennebec 2010-11-08 03:30:06
哈哈,甚至沒有關於DST的事情。不知道它是否適用於此。 – 2010-11-08 03:31:55