|
在 Go 日期比较有什么选择吗?我必须根据日期和时间对数据进行排序 - 独立。因此,只要它也出现在一个时间范围内,我可能会允许一个对象出现在一个日期范围内。在这个模型中,我不能简单地选择最旧的日期、最年轻的时间/最新的日期、最新的时间和 Unix() 秒比较它们。我真的很感激任何建议。
! N3 {+ d/ E, H最后,我写了一个时间分析字符串比较模块来检查时间是否在一定范围内。然而,情况并不好。我有一些悬而未决的问题。我只是想在这里玩,但我希望有更好的时间比较方法。7 q: b/ W5 c2 i- O
package mainimport "strconv" "strings")func tryIndex(arr []string,index int,def string) string if index b and a is the lower limit return false } return false}func timeGreaterEqual(a,b int) (bool,bool) {return a > b,a b}/* * Returns true for two strings formmated "hh:mm:ss". * Note: strings can actually be formatted like "h","hh","hh:m",* "hh:mm",etc. Any missing parts will be added lazily. */func withinTime(timeRange,time string) bool rArr := strings.Split(timeRange,"-") if timeCompare(rArr[0],rArr[1],timeLesserEqual) afterStart := timeCompare(rArr[0],time,timeLesserEqual) beforeEnd := timeCompare(rArr[1],time,timeGreaterEqual) return afterStart && beforeEnd Catch things like `timeRange := "22:00:00-04:59:59"` which will happen // with UTC conversions from local time. // THIS IS THE BROKEN PART I BELIEVE afterStart := timeCompare(rArr[0],time,timeLesserEqual) beforeEnd := timeCompare(rArr[1],time,timeGreaterEqual) return afterStart || beforeEnd}
# Y. U; Q! H; c: K1 K 所以 TLDR,我写了一个 insideTimeRange(range,time) 函数,但它没有完全正常工作。(事实上,主要是第二种情况,即跨越时间范围几天的情况被破坏。原始部分是有效的,我刚刚意识到它正在从当地转变为 UTC 需要考虑这一点。. x S& o5 e" m6 x5 o
如果有更好的方法(最好是内置的),我真的很想听!
m) q5 Q# z3 f8 L) D3 A" N注意:比如我用这个函数 Javascript 解决了这个问题:& z/ L. }2 `- ]' ]% j
function withinTime(start,end,time) var s = Date.parse("01/01/2011 " start); var e = Date.parse("01/0" (end=="24:00:00"?"2":"1") "/2011 " (end=="24:00:00"?"00:00:00":end)); var t = Date.parse("01/01/2011 " time); return s = t;}+ h1 D3 m$ X/ e( z
但我真的很想做这个过滤服务器端。/ n$ h, W& s' _
+ P' y$ H" ^: j% X+ ~0 B 解决方案: 2 E7 p8 A! ?. J# ?/ w
使用time包在 Go 处理时间信息。
/ Q7 D |4 M: X. f9 r1 H8 M% J可以使用 Before、After 和 Equal 方法比较时间瞬间。Sub 方法减去两个时刻,产生一个 Duration。Add 方法添加时间和持续时间,产生时间。( `: g& U1 d4 {1 B
播放示例:
( a) a$ A* t. D" H p. i: w/ o[code]package mainimport "fmt" "time")func inTimeSpan(start,end,check time.Time) bool return check.After(start) && check.Before(end)}func main() start,_ := time.Parse(time.RFC822,"01 Jan 15 10:00 UTC") end,_ := time.Parse(time.RFC822,"01 Jan 16 10:00 UTC") in,_ := time.Parse(time.RFC822,"01 Jan 15 20:00 UTC") out,_ := time.Parse(time.RFC822,"01 Jan 17 10:00 UTC") if inTimeSpan(start,end,in) fmt.Println(in,"is between",start,"and",end,".") } if !inTimeSpan(start,end,out) fmt.Println(out,"is not between",start,"and",end,".") code] |
|