我希望time.Now().In(location)對象在同一時刻比較為相同,即使location對象不同,只要location對象是使用相同的name字符串創建的。為什么這種期望不成立?package mainimport ( "fmt" "time" "log")func main() { const USPacificTimeZone = "US/Pacific" location, err := time.LoadLocation(USPacificTimeZone) if err != nil { log.Fatal(fmt.Sprintf("Couldn't load timezone: %v", err)) } // Exactly the same as location above, just a new instance location2, err := time.LoadLocation(USPacificTimeZone) if err != nil { log.Fatal(fmt.Sprintf("Couldn't load timezone: %v", err)) } now := time.Now() fmt.Printf("Times using same location object: %v\n", now.In(location) == now.In(location)) // prints: Times using same location object: true // Using (the identical) location2 causes the times to be different??? fmt.Printf("Times using different location objects: %v\n", now.In(location) == now.In(location2)) // prints: Times using different location objects: false}
使用兩個不同位置對象的相同時間的時間比較失?。?/h1>
1 回答

阿晨1998
TA貢獻2037條經驗 獲得超6個贊
使用Equal方法比較時間點:
fmt.Printf("Times using different location objects: %v\n", now.In(location).Equal(now.In(location2))) // prints true
Time 類型文檔描述了將 Time 值與 進行比較的陷阱 ==
:
請注意,Go == 運算符不僅比較時間瞬間,還會比較位置和單調時鐘讀數。因此,如果沒有首先保證為所有值設置了相同的位置,時間值不應用作地圖或數據庫鍵,這可以通過使用 UTC 或本地方法來實現,并且單調時鐘讀數已被剝離設置 t = t.Round(0)。一般來說,更喜歡 t.Equal(u) 而不是 t == u,因為 t.Equal 使用可用的最準確的比較,并正確處理只有一個參數具有單調時鐘讀數的情況。
- 1 回答
- 0 關注
- 109 瀏覽
添加回答
舉報
0/150
提交
取消