2016-06-07 100 views
7

有沒有辦法在go上迭代特定月份並從中獲取所有time.Date對象?golang:有沒有辦法在特定的月份或週期內迭代

例如迭代比4月份將導致04012016直到04312016

for _, dayInMonth := range date.April { 
    // do stuff with dates returned 
} 

(目前上面的代碼不會明顯工作)。

或者如果不是標準庫的一部分,是否有第三方庫相當於moment.js

+0

這裏有一個日期包,可能是這個有用:https://github.com/aodin/date – MarsAndBack

回答

14

沒有time.date標準庫中定義的對象。只有time.Time對象。但也沒有辦法範圍循環他們,但手動循環它們是非常簡單的:

// set the starting date (in any way you wish) 
start, err := time.Parse("2006-1-2", "2016-4-1") 
// handle error 

// set d to starting date and keep adding 1 day to it as long as month doesn't change 
for d := start; d.Month() == start.Month(); d = d.AddDate(0, 0, 1) { 
    // do stuff with d 
} 
+0

由於這是一個給我很好的解決方案!請注意,for循環的第三部分應該賦值給d - d = d.AddDate(0,0,1)。 除非你會陷入無限循環。 – Shikloshi

+3

關閉但不會這樣做。 'First Parse()'返回兩個值,所以你需要最小化'start,_:= time.Parse(「2006-1-2」,「2016-4-1」)'想要處理而不是放棄錯誤。第二個'AddDate()'返回一個time.Time,所以要用它來增加d的值,你應該寫'for d:= start; d.Month()== start.Month(); d = d.AddDate(0,0,1)' – Snowman

+1

你當然是對的。我應該更加小心。無論如何,我編輯答案,所以它現在的作品。 – jussius