Пример #1
1
func (self Weekday) NextAfter(t time.Time) (time.Time, error) {
	diff := int(self) - int(t.Weekday())
	if diff <= 0 {
		diff += 7
	}
	return t.AddDate(0, 0, diff), nil
}
Пример #2
0
func main() {
	log.Print("Started running timer")
	var numberOfHours int
	var message string
	isWeekend := false
	var currentTime time.Time
	for {
		numberOfHours += 1
		currentTime = time.Now()
		today := currentTime.Weekday()
		hour := currentTime.Hour()
		isWeekend = today == time.Sunday || today == time.Friday || today == time.Saturday
		switch {
		case (hour >= 22 || hour <= 3) && !isWeekend:
			message = "Late night on a weekday. Sleep!."
		case numberOfHours == 1:
			message = "One hour! Take a break"
		case numberOfHours == 2:
			message = "Two hours! Take a break now."
		case numberOfHours > 2: // or default:
			message = "Take a break now. Seriously."
		}

		log.Print("Sleeping program for one hour")
		time.Sleep(1 * time.Hour)

		showNotification(message)
	}

}
Пример #3
0
// Just like SUBMIT_JOB_BG, but run job at given time instead of
// immediately. This is not currently used and may be removed.
//
// Arguments:
// - NULL byte terminated function name.
// - NULL byte terminated unique ID.
// - NULL byte terminated minute (0-59).
// - NULL byte terminated hour (0-23).
// - NULL byte terminated day of month (1-31).
// - NULL byte terminated month (1-12).
// - NULL byte terminated day of week (0-6, 0 = Monday).
// - Opaque data that is given to the function as an argument.
func (c *Client) SubmitScheduledJob(func_name, uniq string, t time.Time, data []byte) error {

	weekday := int(t.Weekday())

	// go week day number starts at 0 on Sunday,
	// gearman starts at 0 on Monday
	if weekday == 0 {
		weekday = 7
	}
	weekday -= 1

	buf := new(bytes.Buffer)
	buf.WriteString(func_name)
	buf.WriteByte(0)
	buf.WriteString(uniq)
	buf.WriteByte(0)
	buf.WriteString(strconv.Itoa(t.Minute()))
	buf.WriteByte(0)
	buf.WriteString(strconv.Itoa(t.Hour()))
	buf.WriteByte(0)
	buf.WriteString(strconv.Itoa(t.Day()))
	buf.WriteByte(0)
	buf.WriteString(strconv.Itoa(int(t.Month())))
	buf.WriteByte(0)
	buf.WriteString(strconv.Itoa(weekday))
	buf.WriteByte(0)
	buf.Write(data)

	return c.server.Send(CS_SUBMIT_JOB_EPOCH, buf.Bytes())

}
Пример #4
0
// Returns wheter the Timing is active at the specified time
func (rit *RITiming) IsActiveAt(t time.Time) bool {
	// check for years
	if len(rit.Years) > 0 && !rit.Years.Contains(t.Year()) {
		return false
	}
	// check for months
	if len(rit.Months) > 0 && !rit.Months.Contains(t.Month()) {
		return false
	}
	// check for month days
	if len(rit.MonthDays) > 0 && !rit.MonthDays.Contains(t.Day()) {
		return false
	}
	// check for weekdays
	if len(rit.WeekDays) > 0 && !rit.WeekDays.Contains(t.Weekday()) {
		return false
	}
	//log.Print("Time: ", t)

	//log.Print("Left Margin: ", rit.getLeftMargin(t))
	// check for start hour
	if t.Before(rit.getLeftMargin(t)) {
		return false
	}

	//log.Print("Right Margin: ", rit.getRightMargin(t))
	// check for end hour
	if t.After(rit.getRightMargin(t)) {
		return false
	}
	return true
}
Пример #5
0
// func (c *Calendar) ValidOn(date string) bool {
// 	if stringDayDateComp(c.StartDate, date) <= 0 && stringDayDateComp(c.EndDate, date) >= 0 {
func (c *Calendar) ValidOn(intday int, t *time.Time) bool {
	if c.StartDate <= intday && c.EndDate >= intday {

		switch t.Weekday() {
		case time.Monday:
			return c.Monday
		case time.Tuesday:
			return c.Tuesday
		case time.Wednesday:
			return c.Wednesday
		case time.Thursday:
			return c.Thursday
		case time.Friday:
			return c.Friday
		case time.Saturday:
			return c.Saturday
		case time.Sunday:
			return c.Sunday
		default:
			return false
		}

	}

	return false
}
Пример #6
0
func (source mondayAfternoons) GetBetween(start, end time.Time) ([]book.Booking, error) {

	// find next monday
	y, m, d := start.Date()
	daysUntilMonday := int((7 + time.Monday - start.Weekday()) % 7)
	nextmonday := time.Date(y, m, d+daysUntilMonday, 0, 0, 0, 0, start.Location())

	// build a map of booked dates
	bookedSet := make(map[time.Time]bool)
	if booked, err := source.session.List(); err != nil {
		return nil, err
	} else {
		for _, appointment := range booked {
			y, m, d = appointment.Timestamp.Date()
			date := time.Date(y, m, d, 0, 0, 0, 0, start.Location())
			bookedSet[date] = true
		}
	}

	// add a week at a time
	var bookings []book.Booking
	for !nextmonday.After(end) {
		// take days where nothing has been booked yet
		if _, exists := bookedSet[nextmonday]; !exists {
			bookings = append(bookings, lizafternoon{nextmonday})
		}
		nextmonday = nextmonday.AddDate(0, 0, 7)
	}
	return bookings, nil
}
Пример #7
0
// repl replaces % directives with right time, will panic on unknown directive
func repl(match string, t time.Time) string {
	if match == "%%" {
		return "%"
	}

	format, ok := conv[match]
	if ok {
		return t.Format(format)
	}

	switch match {
	case "%j":
		start := time.Date(t.Year(), time.January, 1, 0, 0, 0, 0, time.UTC)
		day := int(t.Sub(start).Hours()/24) + 1
		return fmt.Sprintf("%03d", day)
	case "%w":
		return fmt.Sprintf("%d", t.Weekday())
	case "%W", "%U":
		start := time.Date(t.Year(), time.January, 1, 23, 0, 0, 0, time.UTC)
		week := 0
		for start.Before(t) {
			week += 1
			start = start.Add(WEEK)
		}

		return fmt.Sprintf("%02d", week)
	}

	panic(fmt.Errorf("unknown directive - %s", match))
	return "" // Make compiler happy
}
Пример #8
0
// Times returns the start and stop time for
// the closest Day translation to now.
func (d *Day) Times(now time.Time) (closestStart time.Time, closestStop time.Time) {
	if now.IsZero() {
		Log.Error("Cannot find times without reference")
		return
	}

	if loc, err := d.GetLocation(); loc != nil && err == nil {
		now = now.In(loc)
	}

	// find nearest start time of this slot
	if now.Weekday() == d.Day && todayAt(now, d.Start).Before(now) {
		// if the schedule is for today
		// and we are after that scheduled time,
		// then we have found the closest start
		closestStart = todayAt(now, d.Start)
	} else {
		// Step back a day at a time until we find
		// the most recent day that matches the day
		// of the week of our Day.
		for i := 1; i < 8; i++ {
			sTime := now.Add(-time.Duration(i) * 24 * time.Hour)
			if sTime.Weekday() == d.Day {
				closestStart = todayAt(sTime, d.Start)
				break
			}
		}
	}

	// closestStop is just the closests start plus
	// the duration
	closestStop = closestStart.Add(d.Duration)

	return
}
Пример #9
0
// given a time, calculate the instant that the log should next roll
func calculateNextRollTime(t time.Time, freq rollFrequency) time.Time {
	if freq == RollMinutely {
		t = t.Truncate(time.Minute)
		t = t.Add(time.Minute)
	} else if freq == RollHourly {
		t = t.Truncate(time.Hour)
		t = t.Add(time.Hour)
	} else {
		t = t.Truncate(time.Hour)
		// easiest way to beat DST bugs is to just iterate
		for t.Hour() > 0 {
			t = t.Add(-time.Hour)
		}
		if freq == RollDaily {
			t = t.AddDate(0, 0, 1)
		} else {
			if t.Weekday() == time.Sunday {
				t = t.AddDate(0, 0, 7)
			} else {
				for t.Weekday() != time.Sunday {
					t = t.AddDate(0, 0, 1)
				}
			}
		}
	}

	return t
}
Пример #10
0
func isGametime(t time.Time) bool {
	var start, end time.Time
	year := t.Year()
	month := t.Month()
	day := t.Day()
	hour := t.Hour()
	loc := t.Location()
	switch t.Weekday() {
	case time.Monday, time.Tuesday, time.Wednesday, time.Thursday:
		start = time.Date(year, month, day, 20, 0, 0, 0, loc)
		end = time.Date(year, month, day, 23, 59, 59, 999999999, loc)
	case time.Friday:
		start = time.Date(year, month, day, 19, 0, 0, 0, loc)
		end = time.Date(year, month, day+1, 2, 59, 59, 999999999, loc)
	case time.Saturday:
		if hour < 3 {
			start = time.Date(year, month, day-1, 23, 59, 59, 999999999, loc)
			end = time.Date(year, month, day, 2, 59, 59, 999999999, loc)
		} else {
			start = time.Date(year, month, day, 15, 0, 0, 0, loc)
			end = time.Date(year, month, day+1, 2, 59, 59, 999999999, loc)
		}
	case time.Sunday:
		if hour < 3 {
			start = time.Date(year, month, day-1, 23, 59, 59, 999999999, loc)
			end = time.Date(year, month, day, 2, 59, 59, 999999999, loc)
		} else {
			start = time.Date(year, month, day, 17, 0, 0, 0, loc)
			end = time.Date(year, month, day, 23, 59, 59, 999999999, loc)
		}
	}
	return (t.After(start) && t.Before(end))
}
Пример #11
0
func getDateString(d time.Time) string {
	if d.IsZero() {
		return "Date TBC"
	}

	year, month, day := d.Date()
	suffix := "th"
	switch day % 10 {
	case 1:
		if day%100 != 11 {
			suffix = "st"
		}
	case 2:
		if day%100 != 12 {
			suffix = "nd"
		}
	case 3:
		if day%100 != 13 {
			suffix = "rd"
		}
	}
	return d.Weekday().String() + " " + strconv.Itoa(day) + suffix + " " +
		month.String() + " " + strconv.Itoa(year)

}
Пример #12
0
// FmtDateFull returns the full date representation of 't' for 'ti_ER'
func (ti *ti_ER) FmtDateFull(t time.Time) string {

	b := make([]byte, 0, 32)

	b = append(b, ti.daysWide[t.Weekday()]...)
	b = append(b, []byte{0xe1, 0x8d, 0xa1, 0x20}...)

	if t.Day() < 10 {
		b = append(b, '0')
	}

	b = strconv.AppendInt(b, int64(t.Day()), 10)
	b = append(b, []byte{0x20}...)
	b = append(b, ti.monthsWide[t.Month()]...)
	b = append(b, []byte{0x20, 0xe1, 0x88, 0x98, 0xe1, 0x8b, 0x93, 0xe1, 0x88, 0x8d, 0xe1, 0x89, 0xb2, 0x20}...)
	b = strconv.AppendInt(b, int64(t.Year()), 10)
	b = append(b, []byte{0x20}...)

	if t.Year() < 0 {
		b = append(b, ti.erasWide[0]...)
	} else {
		b = append(b, ti.erasWide[1]...)
	}

	return string(b)
}
Пример #13
0
func (f FileSystem) DateFilepath(date time.Time) string {
	filename := fmt.Sprintf("%s_%s_%d_%d.md", date.Weekday(), date.Month().String(), date.Day(), date.Year())
	path := path.Join(f.MonthDirectory(date), strings.ToLower(filename))
	f.bootstrap(path)

	return path
}
Пример #14
0
// IsWeekdayN reports whether the given date is the nth occurrence of the
// day in the month.
//
// The value of n affects the direction of counting:
//   n > 0: counting begins at the first day of the month.
//   n == 0: the result is always false.
//   n < 0: counting begins at the end of the month.
func IsWeekdayN(date time.Time, day time.Weekday, n int) bool {
	cday := date.Weekday()
	if cday != day || n == 0 {
		return false
	}

	if n > 0 {
		return (date.Day()-1)/7 == (n - 1)
	} else {
		n = -n
		last := time.Date(date.Year(), date.Month()+1,
			1, 12, 0, 0, 0, date.Location())
		lastCount := 0
		for {
			last = last.AddDate(0, 0, -1)
			if last.Weekday() == day {
				lastCount++
			}
			if lastCount == n || last.Month() != date.Month() {
				break
			}
		}
		return lastCount == n && last.Month() == date.Month() &&
			last.Day() == date.Day()
	}
}
Пример #15
0
// IsWorkday reports whether a given date is a work day (business day).
func (c *Calendar) IsWorkday(date time.Time) bool {
	if IsWeekend(date) || c.IsHoliday(date) {
		return false
	}

	if c.Observed == ObservedExact {
		return true
	}

	day := date.Weekday()
	if c.Observed == ObservedMonday && day == time.Monday {
		sun := date.AddDate(0, 0, -1)
		sat := date.AddDate(0, 0, -2)
		return !c.IsHoliday(sat) && !c.IsHoliday(sun)
	} else if c.Observed == ObservedNearest {
		if day == time.Friday {
			sat := date.AddDate(0, 0, 1)
			return !c.IsHoliday(sat)
		} else if day == time.Monday {
			sun := date.AddDate(0, 0, -1)
			return !c.IsHoliday(sun)
		}
	}

	return true
}
Пример #16
0
func (tc *timeClock) isSchoolDay(t time.Time) bool {
	if tc.isHoliday(t) {
		return false
	}
	weekDay := t.Weekday()
	return weekDay >= time.Monday && weekDay <= time.Friday
}
/* Returns the date range used by the Weekday-Weekend prediction hybrid method
   i.e. uses last 5 weekdays if the departure time is on a weekday,
        otherwise uses 7/14/21 days prior to the weekend */
func getWeekdayWeekendDateRange(departureTime time.Time) []time.Time {
	weekday := departureTime.Weekday()
	switch weekday {
	/* Handle case weekday */
	case time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday:
		dateRange := make([]time.Time, 0)
		for i := 1; i <= 7; i++ {
			date := departureTime.AddDate(0, 0, -i)
			if date.Weekday() == time.Saturday || date.Weekday() == time.Sunday {
				continue
			}
			dateRange = append(dateRange, date)
		}
		return dateRange
	/* Handle case weekend */
	case time.Saturday, time.Sunday:
		return []time.Time{
			departureTime.AddDate(0, 0, -7),
			departureTime.AddDate(0, 0, -14),
			departureTime.AddDate(0, 0, -21),
		}
	}
	logger.GetLogger().Panicf("Invalid weekday found: %v", weekday)
	return nil
}
Пример #18
0
func TimeDeltaDowInt(base time.Time, wantDow int, deltaUnits int, wantInclusive bool, wantStartOfDay bool) (time.Time, error) {
	deltaUnitsAbs := deltaUnits
	if deltaUnitsAbs < 1 {
		deltaUnitsAbs *= -1
	}
	deltaDays := int(0)
	if deltaUnits < 0 {
		deltaDaysTry, err := DaysAgoDow(int(base.Weekday()), wantDow, wantInclusive)
		if err != nil {
			return base, err
		}
		deltaDays = deltaDaysTry
	} else if deltaUnits > 0 {
		deltaDaysTry, err := DaysToDow(int(base.Weekday()), wantDow, wantInclusive)
		if err != nil {
			return base, err
		}
		deltaDays = deltaDaysTry
	} else {
		return base, errors.New("Delta units cannot be 0")
	}
	if deltaUnitsAbs > 1 {
		additional := deltaUnitsAbs - 1
		deltaDays += 7 * additional
	}
	if deltaUnits < 0 {
		deltaDays *= -1
	}
	t1 := base.AddDate(0, 0, deltaDays)
	if !wantStartOfDay {
		return t1, nil
	}
	t2 := time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, t1.Location())
	return t2, nil
}
Пример #19
0
func getTimeByRangeType(myTime *time.Time, rangeType dataRangeType) (beginTime time.Time, endTime time.Time) {
	h, m, s := myTime.Clock()
	y, M, d := myTime.Date()
	wd := myTime.Weekday()
	l := myTime.Location()
	var bh, bm, bs, eh, em, es = h, m, s, h, m, s
	var by, bM, bd, ey, eM, ed = y, M, d, y, M, d

	switch rangeType {
	case PerMinute:
		bh, bm, bs = h, m, 0
		eh, em, es = h, m, 59
		by, bM, bd = y, M, d
		ey, eM, ed = y, M, d
	case PerHour:
		bh, bm, bs = h, 0, 0
		eh, em, es = h, 59, 59
		by, bM, bd = y, M, d
		ey, eM, ed = y, M, d
	case PerDay:
		bh, bm, bs = 0, 0, 0
		eh, em, es = 23, 59, 59
		by, bM, bd = y, M, d
		ey, eM, ed = y, M, d
	case PerWeek:
		bh, bm, bs = 0, 0, 0
		eh, em, es = 23, 59, 59
		by, bM, bd = y, M, d-int(time.Sunday+wd)
		ey, eM, ed = y, M, d+int(time.Saturday-wd)
	case PerMonth:
		bh, bm, bs = 0, 0, 0
		eh, em, es = 23, 59, 59
		by, bM, bd = y, M, 1
		ey, eM, ed = y, M+1, 0
	case PerSeason:
		bh, bm, bs = 0, 0, 0
		eh, em, es = 23, 59, 59
		switch {
		case M >= time.January && M <= time.March:
			by, bM, bd = y, 1, 1
		case M >= time.April && M <= time.June:
			by, bM, bd = y, 4, 1
		case M >= time.July && M <= time.September:
			by, bM, bd = y, 7, 1
		case M >= time.October && M <= time.December:
			by, bM, bd = y, 10, 1
		}
		ey, eM, ed = y, bM+3, 0
	case PerYear:
		bh, bm, bs = 0, 0, 0
		eh, em, es = 23, 59, 59
		by, bM, bd = y, 1, 1
		ey, eM, ed = y, 12, 31
	}

	bt := time.Date(by, bM, bd, bh, bm, bs, 0, l)
	et := time.Date(ey, eM, ed, eh, em, es, 999999999, l)

	return bt, et
}
Пример #20
0
func strftime(t time.Time, cfmt string) string {
	sc := newFlagScanner('%', "", "", cfmt)
	for c, eos := sc.Next(); !eos; c, eos = sc.Next() {
		if !sc.ChangeFlag {
			if sc.HasFlag {
				if v, ok := cDateFlagToGo[c]; ok {
					sc.AppendString(t.Format(v))
				} else {
					switch c {
					case 'w':
						sc.AppendString(fmt.Sprint(int(t.Weekday())))
					default:
						sc.AppendChar('%')
						sc.AppendChar(c)
					}
				}
				sc.HasFlag = false
			} else {
				sc.AppendChar(c)
			}
		}
	}

	return sc.String()
}
Пример #21
0
// IsDue check if current moment is match fo expression
func (expr *Expr) IsDue(args ...time.Time) bool {
	var t time.Time

	if len(args) >= 1 {
		t = args[0]
	} else {
		t = time.Now()
	}

	if expr.minutes.index[uint8(t.Minute())] == false {
		return false
	}

	if expr.hours.index[uint8(t.Hour())] == false {
		return false
	}

	if expr.doms.index[uint8(t.Day())] == false {
		return false
	}

	if expr.months.index[uint8(t.Month())] == false {
		return false
	}

	if expr.dows.index[uint8(t.Weekday())] == false {
		return false
	}

	return true
}
Пример #22
0
//时间取整
func TruncDate(cyc string, now time.Time) time.Time { // {{{

	//解析周期并取得距下一周期的时间
	switch {
	case cyc == "ss":
		//按秒取整
		return time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), 0, time.Local)
	case cyc == "mi":
		//按分钟取整
		return time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), 0, 0, time.Local)

	case cyc == "h":
		//按小时取整
		return time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, time.Local)
	case cyc == "d":
		//按日取整
		return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
	case cyc == "m":
		//按月取整
		return time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.Local)
	case cyc == "w":
		//按周取整
		return time.Date(now.Year(), now.Month(), now.Day()-int(now.Weekday()), 0, 0, 0, 0, time.Local)
	case cyc == "q":
		//回头再处理
	case cyc == "y":
		//按年取整
		return time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.Local)
	}
	return time.Now()

} // }}}
Пример #23
0
func (f FileSystem) WeekFilepath(date time.Time) string {
	start := date.AddDate(0, 0, -1*int(date.Weekday()))
	year, month, day := start.Date()
	filename := strings.ToLower(fmt.Sprintf("week_%s_%d_%d.md", month.String(), day, year))
	path := path.Join(f.MonthDirectory(start), filename)
	f.bootstrap(path)
	return path
}
Пример #24
0
// StartOfWeek returns the start of the current week for the time.
func StartOfWeek(t time.Time) time.Time {
	// Figure out number of days to back up until Mon:
	// Sun is 0 -> 6, Sat is 6 -> 5, etc.
	toMon := Weekday(t.Weekday())
	y, m, d := t.AddDate(0, 0, -int(toMon)).Date()
	// Result is 00:00:00 on that year, month, day.
	return time.Date(y, m, d, 0, 0, 0, 0, t.Location())
}
Пример #25
0
// WeekdayInList tests if the weekday of a time is in a given list.
func WeekdayInList(t time.Time, weekdays []time.Weekday) bool {
	for _, weekday := range weekdays {
		if t.Weekday() == weekday {
			return true
		}
	}
	return false
}
Пример #26
0
func (job *Job) HappensOn(t *time.Time) bool {
	freq := job.Msg.GetFrequency()

	return int8(freq.GetWeekday()) == int8(t.Weekday()) ||
		freq.GetWeekday() == -1 &&
			freq.GetMonth() == int32(t.Month()) &&
			freq.GetDay() == int32(t.Day())
}
Пример #27
0
// Matches returns true if the job time has arrived (Alarm clock rings)
func (cj job) Matches(t time.Time) (ok bool) {
	return (cj.Month == any || cj.Month == int8(t.Month())) &&
		(cj.Day == any || cj.Day == int8(t.Day())) &&
		(cj.Weekday == any || cj.Weekday == int8(t.Weekday())) &&
		(cj.Hour == any || cj.Hour == int8(t.Hour())) &&
		(cj.Minute == any || cj.Minute == int8(t.Minute())) &&
		(cj.Second == any || cj.Second == int8(t.Second()))
}
Пример #28
0
func getWeekdayNum(d time.Time) int {
	r := int(d.Weekday())

	if r == 0 {
		r = 7
	}

	return r
}
Пример #29
0
func (q *TQuery) Match(t time.Time) bool {
	idxs := []int{t.Minute(), t.Hour(), t.Day(), int(t.Month()), int(t.Weekday())}
	for i, idx := range idxs {
		if !q.fields[i].Test(uint(idx)) {
			return false
		}
	}
	return true
}
Пример #30
0
func (l *dateLexer) resolveDay(rel time.Time) time.Time {
	y, m, _ := rel.Date()
	h, n, s := rel.Clock()
	rel = time.Date(y, m, l.day, h, n, s, 0, rel.Location())
	if DEBUG {
		fmt.Printf("Parsed day as %s %s\n", rel.Weekday(), rel)
	}
	return rel
}