Is there a way, in go
, to iterate over a specific month and get all time.Date
objects from it?
For instance iterate over April will result in 04012016
until 04312016
:
for _, dayInMonth := range date.April {
// do stuff with dates returned
}
(Currently the above code will not work obviously).
Or if not part of the standard library is there a third party library that equivalent to moment.js?
There is no time.Date object defined in the standard library. Only time.Time object. There's also no way to range loop them, but looping them manually is quite simple:
// 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
}
@jessius way can only work if the iteration is within a month. Better way to iterate is to use epoch format of the time.
for example, for oneDay we know it is 86400 seconds. we can do follwing
oneDay := int64(86400) // a day in seconds.
startDate := int64(1519862400)
endDate := int64(1520640000)
for timestamp := startDate; timestamp <= endDate; timestamp += oneDay {
// do your work
}
Simple and workable for iterating days.
For month, this way cannot work, because each month has different days. I only have similar ideas as @jussius, but tweak to apply to month iteration.
I'm keen to compare the dates
func LeqDates(a, b time.Time) bool {
year1, month1, day1 := a.Date()
year2, month2, day2 := b.Date()
if year1 < year2 {
return true
} else if year1 <= year2 && month1 < month2 {
return true
} else {
return year1 <= year2 && month1 <= month2 && day1 <= day2
}
}