77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
|
package meetup
|
||
|
|
||
|
import "time"
|
||
|
|
||
|
const testVersion = 3
|
||
|
|
||
|
type WeekSchedule int
|
||
|
|
||
|
const (
|
||
|
First WeekSchedule = iota
|
||
|
Second
|
||
|
Third
|
||
|
Fourth
|
||
|
Last
|
||
|
Teenth
|
||
|
)
|
||
|
|
||
|
// Day calculates which day of the month the requested day falls on
|
||
|
func Day(week WeekSchedule, weekday time.Weekday, month time.Month, year int) int {
|
||
|
var t time.Time
|
||
|
switch week {
|
||
|
case First:
|
||
|
t = time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
|
||
|
if t.Weekday() == weekday {
|
||
|
return t.Day()
|
||
|
}
|
||
|
case Second:
|
||
|
t = time.Date(year, month, 8, 0, 0, 0, 0, time.UTC)
|
||
|
if t.Weekday() == weekday {
|
||
|
return t.Day()
|
||
|
}
|
||
|
case Third:
|
||
|
t = time.Date(year, month, 15, 0, 0, 0, 0, time.UTC)
|
||
|
if t.Weekday() == weekday {
|
||
|
return t.Day()
|
||
|
}
|
||
|
case Fourth:
|
||
|
t = time.Date(year, month, 22, 0, 0, 0, 0, time.UTC)
|
||
|
if t.Weekday() == weekday {
|
||
|
return t.Day()
|
||
|
}
|
||
|
case Last:
|
||
|
t = time.Date(year, month+1, 1, 0, 0, 0, 0, time.UTC)
|
||
|
t = t.AddDate(0, 0, -1)
|
||
|
if t.Weekday() == weekday {
|
||
|
return t.Day()
|
||
|
}
|
||
|
return findPrevDay(weekday, t).Day()
|
||
|
case Teenth:
|
||
|
t = time.Date(year, month, 13, 0, 0, 0, 0, time.UTC)
|
||
|
if t.Weekday() == weekday {
|
||
|
return t.Day()
|
||
|
}
|
||
|
}
|
||
|
return findNextDay(weekday, t).Day()
|
||
|
}
|
||
|
|
||
|
// findNextDay finds the next 'weekday' after t
|
||
|
func findNextDay(weekday time.Weekday, t time.Time) time.Time {
|
||
|
t = t.AddDate(0, 0, 1)
|
||
|
dow := t.Weekday()
|
||
|
for ; dow != weekday; dow = t.Weekday() {
|
||
|
t = t.AddDate(0, 0, 1)
|
||
|
}
|
||
|
return t
|
||
|
}
|
||
|
|
||
|
// findPrevDay finds the previous 'weekday' before t
|
||
|
func findPrevDay(weekday time.Weekday, t time.Time) time.Time {
|
||
|
t = t.AddDate(0, 0, -1)
|
||
|
dow := t.Weekday()
|
||
|
for ; dow != weekday; dow = t.Weekday() {
|
||
|
t = t.AddDate(0, 0, -1)
|
||
|
}
|
||
|
return t
|
||
|
}
|