// Count the number of days in the provided date range. func (this *DayCounter) Count() (int, error) { var days []time.Weekday // If no weekdays have been supplied count all the weekdays if len(this.days) == 0 { log.Printf("Setting all days.") for i := 0; i < 7; i++ { log.Printf("Adding day: %v", time.Weekday(i)) days = append(days, time.Weekday(i)) } } else { days = this.days } var nr int day := this.From for { if this.To.Before(day) { log.Printf("Reached end date: %v", this.To) break } if match(day.Weekday(), days) { log.Printf("Matched day: %v", day.Weekday()) nr++ } day = day.AddDate(0, 0, 1) } return nr, nil }
func makeISOTimeArray(startDate time.Time, endDate time.Time) []stock.ISOTime { var timeArray []stock.ISOTime // Make sure startDate and endDate are in 2011/2012, those are the only years // that we have holiday information for. If not, return empy. if !(startDate.Year() == 2011 || startDate.Year() == 2012) && (endDate.Year() == 2011 || endDate.Year() == 2012) { return timeArray } var day stock.ISOTime = stock.ISOTime{startDate.AddDate(0, 0, -1)} for day.Before(endDate) { day = stock.ISOTime{day.AddDate(0, 0, 1)} // market is not open on Saturday or Sunday if day.Weekday() == time.Weekday(0) || day.Weekday() == time.Weekday(6) { continue } // market is not open on certain holidays isHoliday := false for _, holiday := range Holidays20112012 { if day.Year() == holiday.Year() && day.YearDay() == holiday.YearDay() { isHoliday = true break } } if !isHoliday { timeArray = append(timeArray, day) } } return timeArray }
func (d Day) String() (s string) { if d.number == today { s += "\x1b[1;37m" + time.Weekday(d.number%7).String() + "\x1b[0m:\n" } else { s += time.Weekday(d.number%7).String() + ":\n" } for _, e := range d.entries { s += e.String() } return }
func TestDaysAbbreviated(t *testing.T) { trans := New() days := trans.WeekdaysAbbreviated() for i, day := range days { s := trans.WeekdayAbbreviated(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ { idx: 0, expected: "Sun", }, { idx: 1, expected: "Mon", }, { idx: 2, expected: "Tue", }, { idx: 3, expected: "Wed", }, { idx: 4, expected: "Thu", }, { idx: 5, expected: "Fri", }, { idx: 6, expected: "Sat", }, } for _, tt := range tests { s := trans.WeekdayAbbreviated(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
func TestDaysShort(t *testing.T) { trans := New() days := trans.WeekdaysShort() for i, day := range days { s := trans.WeekdayShort(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Su", // }, // { // idx: 1, // expected: "Mo", // }, // { // idx: 2, // expected: "Tu", // }, // { // idx: 3, // expected: "We", // }, // { // idx: 4, // expected: "Th", // }, // { // idx: 5, // expected: "Fr", // }, // { // idx: 6, // expected: "Sa", // }, } for _, tt := range tests { s := trans.WeekdayShort(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
func TestDaysWide(t *testing.T) { trans := New() days := trans.WeekdaysWide() for i, day := range days { s := trans.WeekdayWide(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ { idx: 0, expected: "воскресенье", }, { idx: 1, expected: "понедельник", }, { idx: 2, expected: "вторник", }, { idx: 3, expected: "среда", }, { idx: 4, expected: "четверг", }, { idx: 5, expected: "пятница", }, { idx: 6, expected: "суббота", }, } for _, tt := range tests { s := trans.WeekdayWide(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
func TestDaysShort(t *testing.T) { trans := New() days := trans.WeekdaysShort() for i, day := range days { s := trans.WeekdayShort(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ { idx: 0, expected: "вс", }, { idx: 1, expected: "пн", }, { idx: 2, expected: "вт", }, { idx: 3, expected: "ср", }, { idx: 4, expected: "чт", }, { idx: 5, expected: "пт", }, { idx: 6, expected: "сб", }, } for _, tt := range tests { s := trans.WeekdayShort(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
func (l *dateLexer) setDay(d, n int, year ...int) { if DEBUG { fmt.Printf("Setting day to %d %s\n", n, time.Weekday(d)) } if l.state(HAVE_DAYS, true) { l.Error("Parsed two days") } l.days = relDays{time.Weekday(d), n, 0} if len(year) > 0 { l.days.year = year[0] } }
func TestDaysNarrow(t *testing.T) { trans := New() days := trans.WeekdaysNarrow() for i, day := range days { s := trans.WeekdayNarrow(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", string(day), s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "S", // }, // { // idx: 1, // expected: "M", // }, // { // idx: 2, // expected: "T", // }, // { // idx: 3, // expected: "W", // }, // { // idx: 4, // expected: "T", // }, // { // idx: 5, // expected: "F", // }, // { // idx: 6, // expected: "S", // }, } for _, tt := range tests { s := trans.WeekdayNarrow(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
func TestDaysWide(t *testing.T) { trans := New() days := trans.WeekdaysWide() for i, day := range days { s := trans.WeekdayWide(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sunday", // }, // { // idx: 1, // expected: "Monday", // }, // { // idx: 2, // expected: "Tuesday", // }, // { // idx: 3, // expected: "Wednesday", // }, // { // idx: 4, // expected: "Thursday", // }, // { // idx: 5, // expected: "Friday", // }, // { // idx: 6, // expected: "Saturday", // }, } for _, tt := range tests { s := trans.WeekdayWide(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
func bestRanking(stop chan bool) RankingAlgorithm { return func(c *Schedule) float64 { select { case <-stop: stop <- true return 0.0 default: // Get a point for every class that isn't 8-12 earlyPoints := 0.0 for day := 1; day < 6; day++ { earlyClasses, _ := time.Parse("3:04PM", "8:00AM") for i := 0; i < 16; i++ { _, _, hasClass := c.ClassAtTime(earlyClasses, time.Weekday(day)) if !hasClass { earlyPoints += 1 } else { break } earlyClasses = earlyClasses.Add(time.Minute * 15) } } // Another point for every class that isn't 11:30-2 (30 minute increments) lunchPoints := 0.0 for day := 1; day < 6; day++ { lunchClasses, _ := time.Parse("3:04PM", "11:30AM") for i := 0; i < 10; i++ { _, _, hasStartClass := c.ClassAtTime(lunchClasses.Add(time.Minute), time.Weekday(day)) _, _, hasEndClass := c.ClassAtTime(lunchClasses.Add(time.Minute*29), time.Weekday(day)) if !hasStartClass && !hasEndClass { lunchPoints += 1 } lunchClasses = lunchClasses.Add(time.Minute * 15) } } // Another point for every class that isn't 3-10 latePoints := 0.0 for day := 1; day < 6; day++ { lateClasses, _ := time.Parse("3:04PM", "10:00PM") for i := 0; i < 28; i++ { _, _, hasClass := c.ClassAtTime(lateClasses, time.Weekday(day)) if !hasClass { latePoints += 1 } else { break } lateClasses = lateClasses.Add(time.Minute * -15) } } return (latePoints + earlyPoints + lunchPoints) } } }
func (s *TimeUtilSuite) TestDateNames(c *C) { c.Assert(getShortWeekday(time.Sunday), Equals, "Sun") c.Assert(getShortWeekday(time.Monday), Equals, "Mon") c.Assert(getShortWeekday(time.Tuesday), Equals, "Tue") c.Assert(getShortWeekday(time.Wednesday), Equals, "Wed") c.Assert(getShortWeekday(time.Thursday), Equals, "Thu") c.Assert(getShortWeekday(time.Friday), Equals, "Fri") c.Assert(getShortWeekday(time.Saturday), Equals, "Sat") c.Assert(getShortWeekday(time.Weekday(7)), Equals, "") c.Assert(getLongWeekday(time.Sunday), Equals, "Sunday") c.Assert(getLongWeekday(time.Monday), Equals, "Monday") c.Assert(getLongWeekday(time.Tuesday), Equals, "Tuesday") c.Assert(getLongWeekday(time.Wednesday), Equals, "Wednesday") c.Assert(getLongWeekday(time.Thursday), Equals, "Thursday") c.Assert(getLongWeekday(time.Friday), Equals, "Friday") c.Assert(getLongWeekday(time.Saturday), Equals, "Saturday") c.Assert(getLongWeekday(time.Weekday(7)), Equals, "") c.Assert(getShortMonth(time.Month(0)), Equals, "") c.Assert(getShortMonth(time.January), Equals, "Jan") c.Assert(getShortMonth(time.February), Equals, "Feb") c.Assert(getShortMonth(time.March), Equals, "Mar") c.Assert(getShortMonth(time.April), Equals, "Apr") c.Assert(getShortMonth(time.May), Equals, "May") c.Assert(getShortMonth(time.June), Equals, "Jun") c.Assert(getShortMonth(time.July), Equals, "Jul") c.Assert(getShortMonth(time.August), Equals, "Aug") c.Assert(getShortMonth(time.September), Equals, "Sep") c.Assert(getShortMonth(time.October), Equals, "Oct") c.Assert(getShortMonth(time.November), Equals, "Nov") c.Assert(getShortMonth(time.December), Equals, "Dec") c.Assert(getLongMonth(time.Month(0)), Equals, "") c.Assert(getLongMonth(time.January), Equals, "January") c.Assert(getLongMonth(time.February), Equals, "February") c.Assert(getLongMonth(time.March), Equals, "March") c.Assert(getLongMonth(time.April), Equals, "April") c.Assert(getLongMonth(time.May), Equals, "May") c.Assert(getLongMonth(time.June), Equals, "June") c.Assert(getLongMonth(time.July), Equals, "July") c.Assert(getLongMonth(time.August), Equals, "August") c.Assert(getLongMonth(time.September), Equals, "September") c.Assert(getLongMonth(time.October), Equals, "October") c.Assert(getLongMonth(time.November), Equals, "November") c.Assert(getLongMonth(time.December), Equals, "December") c.Assert(getWeekdayNum(time.Unix(1448193600, 0)), Equals, 7) }
func handleUpdate(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) var ( d int day time.Weekday err error ) // Check if there is a signed in user. u := currentUser(r) if u == nil { aelog.Errorf(c, "No signed in user for updating") goto out } // Validate XSRF token first. if !xsrftoken.Valid(r.PostFormValue(xsrfTokenName), xsrfKey, u.ID, updateURL) { aelog.Errorf(c, "XSRF token validation failed") goto out } // Extract the new favorite weekday. d, err = strconv.Atoi(r.PostFormValue(favoriteName)) if err != nil { aelog.Errorf(c, "Failed to extract new favoriate weekday: %s", err) goto out } day = time.Weekday(d) if day < time.Sunday || day > time.Saturday { aelog.Errorf(c, "Got wrong value for favorite weekday: %d", d) } // Update the favorite weekday. updateWeekdayForUser(r, u, day) out: // Redirect to home page to show the update result. http.Redirect(w, r, homeURL, http.StatusFound) }
// This function returns true or false, depending on whether the CacheTimeout // value has expired or not. Additionally, it will ensure that we adhere to the // RSS spec's SkipDays and SkipHours values (if Feed.EnforceCacheLimit is set to // true). If this function returns true, you can be sure that a fresh feed // update will be performed. func (this *Feed) CanUpdate() bool { // Make sure we are not within the specified cache-limit. // This ensures we don't request data too often. utc := time.Now().UTC() if utc.UnixNano()-this.lastupdate < int64(this.CacheTimeout*60) { return false } // If skipDays or skipHours are set in the RSS feed, use these to see if // we can update. if len(this.Channels) == 1 && this.Type == "rss" { if this.EnforceCacheLimit && len(this.Channels[0].SkipDays) > 0 { for _, v := range this.Channels[0].SkipDays { if time.Weekday(v) == utc.Weekday() { return false } } } if this.EnforceCacheLimit && len(this.Channels[0].SkipHours) > 0 { for _, v := range this.Channels[0].SkipHours { if v == utc.Hour() { return false } } } } this.lastupdate = utc.UnixNano() return true }
/* Returns timetable for specified line, bound and stop in the form of a map map (weekday => []("hour" => hour "minute" => minute)) */ func SelectTimetable(line, bound, naptanId string) map[time.Weekday]map[LocalTime]bool { var timetable []TimetableEntry dbconn.AcquireLock() err := db.Select(&timetable, "SELECT weekday, departure_time FROM timetable WHERE line_id=$1 AND bound=$2 AND naptan_id=$3 ORDER BY weekday,departure_time", line, bound, naptanId) dbconn.ReleaseLock() if err != nil { logger.GetLogger().Panic(err) } result := make(map[time.Weekday]map[LocalTime]bool) for _, entry := range timetable { weekday := time.Weekday(entry.Weekday) weekdayMap, exists := result[weekday] if !exists { weekdayMap = make(map[LocalTime]bool, 0) result[weekday] = weekdayMap } weekdayMap[LocalTime{Hour: entry.DepartureTime.Hour(), Minute: entry.DepartureTime.Minute()}] = true } logger.GetLogger().Info("Get timetable for line %v (%v), stop %v returned: %v", line, bound, naptanId, result) return result }
// Add involving the special "|" syntax. func addSpecial(f fields, date time.Time) time.Time { // move to the 1st of the appropriate month date = time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.UTC) if f.repeatUnit == "m" { date = date.AddDate(0, 1, 0) } else { date = date.AddDate(1, 0, 0) } // build up a list of candidate days in that month days := []time.Time{} for d := date; d.Month() == date.Month(); { if d.Weekday() == time.Weekday(strings.Index(weekdays, f.specialWeekday)) { days = append(days, d) } d = d.AddDate(0, 0, 1) } // return the right candidate index := atoi(f.specialSign+f.repeatAmount) - 1 if index < 0 { index += len(days) + 1 } return days[index] }
// This function returns true or false, depending on whether the CacheTimeout // value has expired or not. Additionally, it will ensure that we adhere to the // RSS spec's SkipDays and SkipHours values. If this function returns true, you // can be sure that a fresh feed update will be performed. func (f *Feed) CanUpdate() bool { // Make sure we are not within the specified cache-limit. // This ensures we don't request data too often. utc := time.Now().UTC() if utc.Sub(f.lastupdate) < f.cacheTimeout { return false } // If skipDays or skipHours are set in the RSS feed, use these to see if // we can update. if len(f.channels) == 1 && f.format == "rss" { if len(f.channels[0].SkipDays) > 0 { for _, v := range f.channels[0].SkipDays { if time.Weekday(v) == utc.Weekday() { return false } } } if len(f.channels[0].SkipHours) > 0 { for _, v := range f.channels[0].SkipHours { if v == utc.Hour() { return false } } } } f.lastupdate = utc return true }
func ask(d time.Time) int { var i int fmt.Scan(&i) for i > 6 { fmt.Printf("Reduced? ") fmt.Scan(&i) } if time.Weekday(i) != d.Weekday() { fmt.Printf("✗ not %s ", time.Weekday(i)) return ask(d) } return i }
// todo panic? func (m *Moment) Weekday(index int) string { if index > 6 { panic("Weekday index must be between 0 and 6") } return time.Weekday(index).String() }
func (sp *SemesterPlan) ForAllWeekdays(fn func(string, time.Weekday, int, string) string) string { s := "" for day := 0; day < 7; day++ { for hour := FIRSTHOUR; hour <= LASTHOUR; hour++ { for _, persplan := range sp.personPlans { for _, personday := range persplan.workdays { if personday.dayoftheweek == time.Weekday(day) { if (hour >= personday.fromHour) && (hour < personday.uptoHour) { s += fn(persplan.who, time.Weekday(day), hour, personday.location) } } } } } } return s }
func init() { loweredMonths = append(loweredMonths, "") for m := 1; m <= 12; m++ { loweredMonths = append(loweredMonths, strings.ToLower(time.Month(m).String())) } for w := 0; w <= 6; w++ { loweredWeekdays = append(loweredWeekdays, strings.ToLower(time.Weekday(w).String())) } }
func parseDay(day string) ([]time.Weekday, error) { d, ok := weekdays[day] if !ok { return nil, fmt.Errorf("%v is not a valid weekday. (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)", day) } return []time.Weekday{time.Weekday(d)}, nil }
func parseWeekday(s string) (time.Weekday, error) { idx, err := strconv.ParseInt(s, 10, 0) if err != nil { return 0, err } if idx < 0 || idx > 6 { return 0, fmt.Errorf("out of range") } return time.Weekday(idx), nil }
func createWeekdaysFeature(val map[string]interface{}) (Feature, bool) { if daysRaw, ok := val[WeekdaysKey]; ok { activeOnWeekdays := make(map[time.Weekday]bool) days := strings.Split(daysRaw.(string), " | ") for i := 0; i < 7; i = i + 1 { activeOnWeekdays[time.Weekday(i)] = false for _, day := range days { if time.Weekday(i).String() == day { activeOnWeekdays[time.Weekday(i)] = true } } } pred := func() bool { return activeOnWeekdays[time.Now().Weekday()] } return newPredicateFeature(pred), true } return nil, false }
func (ns *NickStat) MostActive() (day time.Weekday, hour int, count int) { for d, times := range ns.Active { for h, c := range times { if c > count { day = time.Weekday(d) hour = h count = c } } } return }
func (wd *WeekDays) Parse(input, sep string) { switch input { case "*any", "": *wd = []time.Weekday{} default: elements := strings.Split(input, sep) for _, wds := range elements { if day, err := strconv.Atoi(wds); err == nil { *wd = append(*wd, time.Weekday(day%7)) // %7 for sunday = 7 normalization } } } }
func run_per_week(ch chan time.Time, wk int) { var dur time.Duration = 1 * time.Hour day := time.Now().Weekday() if day == time.Weekday(wk) { dur = 24 * time.Hour } for { day = time.Now().Weekday() if day != time.Weekday(wk) { time.Sleep(dur) dur = 1 * time.Hour } else { ch <- time.Now() return } } }
func getNextWeekdayOccurance(paramString string) time.Time { var inputString = strings.TrimSpace(paramString) now := time.Now() for i := 0; i < 7; i++ { weekday := time.Weekday(i) if strings.ToLower(inputString) == strings.ToLower(weekday.String()) { daysUntilRequestedDay := (int(weekday) - int(now.Weekday()) + 7) % 7 t := easyTime{now.AddDate(0, 0, daysUntilRequestedDay)} return t.beginningOfDay() } } return time.Now() }
func handleUpdate(w http.ResponseWriter, r *http.Request) { operationResult := "failure" outFunc := func() { http.Redirect(w, r, successLandingURL+"?update="+operationResult, http.StatusFound) } var ( d int day time.Weekday err error ) // Generic c := appengine.NewContext(r) // Check if there is a signed in user. u := CurrentUser(r) if u == nil { aelog.Errorf(c, "No signed in user for updating") outFunc() goto out } // Validate XSRF token first. if !xsrftoken.Valid(r.PostFormValue(xsrfTokenName), xsrfKey, u.ID, updateURL) { aelog.Errorf(c, "XSRF token validation failed") outFunc() goto out } // // Specific // Extract the new favorite weekday. d, err = strconv.Atoi(r.PostFormValue(fieldNameFavWeekDay)) if err != nil { aelog.Errorf(c, "Failed to extract new favoriate weekday: %s", err) outFunc() goto out } day = time.Weekday(d) if day < time.Sunday || day > time.Saturday { aelog.Errorf(c, "Got wrong value for favorite weekday: %d", d) outFunc() goto out } // Update the favorite weekday. updateWeekdayForUser(r, u, day) operationResult = "success" out: outFunc() }
func TestNextOccurrenceOfWeekday(t *testing.T) { input := time.Date(2001, 2, 3, 4, 5, 6, 7, time.UTC) expected := input result := NewSimpleTime(input).NextOccurrenceOfWeekday(input.Weekday()) if result != expected { t.Errorf("TestNextOccurrenceOfWeekday Failed:\nInput=(%v),\nExpected=(%v),\nResult=(%v)", input, expected, result) } expected = time.Date(2001, 2, 9, 0, 0, 0, 0, time.UTC) result = NewSimpleTime(input).NextOccurrenceOfWeekday(time.Weekday(5)) if result != expected { t.Errorf("TestNextOccurrenceOfWeekday Failed:\nInput=(%v),\nExpected=(%v),\nResult=(%v)", input, expected, result) } }