Exemple #1
0
func (f Frequency) addTo(t time.Time, mul uint) time.Time {
	sec := t.Second()
	min := t.Minute()
	hour := t.Hour()
	day := t.Day()
	month := t.Month()
	year := t.Year()
	loc := t.Location()

	fq := int(f.Count * mul)

	switch f.Unit {
	case Minute:
		return t.Add(time.Minute * time.Duration(fq))
	case Hour:
		return t.Add(time.Hour * time.Duration(fq))
	case Day:
		return time.Date(year, month, day+fq, hour, min, sec, 0, loc)
	case Week:
		return time.Date(year, month, day+fq*7, hour, min, sec, 0, loc)
	case Month:
		return time.Date(year, month+time.Month(fq), day, hour, min, sec, 0, loc)
	case Year:
		return time.Date(year+fq, month, day, hour, min, sec, 0, loc)
	default:
		return nilTime
	}
}
Exemple #2
0
func (w *Writer) writeTime(v interface{}, t time.Time) (err error) {
	w.setRef(v)
	s := w.Stream
	year, month, day := t.Date()
	hour, min, sec := t.Clock()
	nsec := t.Nanosecond()
	tag := TagSemicolon
	if t.Location() == time.UTC {
		tag = TagUTC
	}
	if hour == 0 && min == 0 && sec == 0 && nsec == 0 {
		if _, err = s.Write(formatDate(year, int(month), day)); err == nil {
			err = s.WriteByte(tag)
		}
	} else if year == 1970 && month == 1 && day == 1 {
		if _, err = s.Write(formatTime(hour, min, sec, nsec)); err == nil {
			err = s.WriteByte(tag)
		}
	} else if _, err = s.Write(formatDate(year, int(month), day)); err == nil {
		if _, err = s.Write(formatTime(hour, min, sec, nsec)); err == nil {
			err = s.WriteByte(tag)
		}
	}
	return err
}
Exemple #3
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
}
Exemple #4
0
// creates a new caldav datetime representation, must be in UTC
func NewDateTime(name string, t time.Time) (*DateTime, error) {
	if t.Location() != time.UTC {
		return nil, errors.New("CalDAV datetime must be in UTC")
	} else {
		return &DateTime{name: name, t: t.Truncate(time.Second)}, nil
	}
}
Exemple #5
0
func ParseTime(str string, rel time.Time) time.Time {
	if t, ok := tryAll(str, rel, datetimeFormats); ok {
		return t
	}

	var dt, tt time.Time
	var dok, tok bool
	if strings.Index(str, " ") > -1 {
		parts := strings.SplitN(str, " ", 2)
		dt, dok = tryAll(parts[0], rel, dateFormats)
		tt, tok = tryAll(parts[1], rel, timeFormats)
	}
	if !dok || !tok {
		dt, dok = tryAll(str, rel, dateFormats)
		tt, tok = tryAll(str, rel, timeFormats)
	}
	if !dok && !tok {
		return time.Time{}
	}

	y, mo, d := dt.Date()
	if y == 0 {
		y, _, _ = rel.Date()
	}
	h, m, s := tt.Clock()
	return time.Date(y, mo, d, h, m, s, 0, rel.Location())
}
Exemple #6
0
func (self Day) NextAfter(t time.Time) (time.Time, error) {
	desiredDay := int(self)

	if desiredDay == Last {
		if isLastDayInMonth(t) {
			return t.AddDate(0, 0, 1).AddDate(0, 1, -1), nil
		}

		return firstDayOfMonth(t).AddDate(0, 2, -1), nil
	}

	if t.Day() > desiredDay {
		if isLastDayInMonth(t) && desiredDay == First {
			return t.AddDate(0, 0, 1), nil
		}

		return self.NextAfter(t.AddDate(0, 0, 1))
	}

	if t.Day() < desiredDay {
		totalDays := lastDayOfMonth(t).Day()
		if totalDays < desiredDay {
			return self.NextAfter(t.AddDate(0, 1, 0))
		}

		return time.Date(t.Year(), t.Month(), desiredDay, 0, 0, 0, 0, t.Location()), nil
	}

	totalDaysNextMonth := lastDayOfMonth(lastDayOfMonth(t).AddDate(0, 0, 1)).Day()
	if totalDaysNextMonth < desiredDay {
		return self.NextAfter(t.AddDate(0, 2, -1))
	}

	return t.AddDate(0, 1, 0), nil
}
Exemple #7
0
func (expr *Expression) nextMonth(t time.Time) time.Time {
	// Find index at which item in list is greater or equal to
	// candidate month
	i := sort.SearchInts(expr.monthList, int(t.Month())+1)
	if i == len(expr.monthList) {
		return expr.nextYear(t)
	}
	// Month changed, need to recalculate actual days of month
	expr.actualDaysOfMonthList = expr.calculateActualDaysOfMonth(t.Year(), expr.monthList[i])
	if len(expr.actualDaysOfMonthList) == 0 {
		return expr.nextMonth(time.Date(
			t.Year(),
			time.Month(expr.monthList[i]),
			1,
			expr.hourList[0],
			expr.minuteList[0],
			expr.secondList[0],
			0,
			t.Location()))
	}

	return time.Date(
		t.Year(),
		time.Month(expr.monthList[i]),
		expr.actualDaysOfMonthList[0],
		expr.hourList[0],
		expr.minuteList[0],
		expr.secondList[0],
		0,
		t.Location())
}
Exemple #8
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()
	}
}
Exemple #9
0
//	从雅虎财经获取上市公司分时数据
func DownloadCompanyDaily(marketName, companyCode, queryCode string, day time.Time) error {

	//	检查数据库是否解析过,解析过的不再重复解析
	found := raw60Exists(marketName, companyCode, day)
	if found {
		return nil
	}

	//	如果不存在就抓取
	start := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, day.Location())
	end := start.Add(time.Hour * 24)

	pattern := "https://finance-yql.media.yahoo.com/v7/finance/chart/%s?period2=%d&period1=%d&interval=1m&indicators=quote&includeTimestamps=true&includePrePost=true&events=div%7Csplit%7Cearn&corsDomain=finance.yahoo.com"
	url := fmt.Sprintf(pattern, queryCode, end.Unix(), start.Unix())

	//	查询Yahoo财经接口,返回股票分时数据
	content, err := io.DownloadStringRetry(url, retryTimes, retryIntervalSeconds)
	if err != nil {
		return err
	}

	raw := Raw60{
		Market:  marketName,
		Code:    companyCode,
		Date:    day.UTC(),
		Json:    content,
		Status:  0,
		Message: ""}

	//	保存(加入保存队列)
	saveQueue <- raw

	return nil
}
Exemple #10
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
}
Exemple #11
0
// Crawl 获取公司每天的报价
func (yahoo YahooFinance) Crawl(_market market.Market, company market.Company, date time.Time) (*market.CompanyDailyQuote, error) {

	// 起止时间
	start := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
	end := start.AddDate(0, 0, 1)

	pattern := "https://finance-yql.media.yahoo.com/v7/finance/chart/%s?period2=%d&period1=%d&interval=1m&indicators=quote&includeTimestamps=true&includePrePost=true&events=div%%7Csplit%%7Cearn&corsDomain=finance.yahoo.com"
	url := fmt.Sprintf(pattern, _market.YahooQueryCode(company), end.Unix(), start.Unix())

	// 查询Yahoo财经接口,返回股票分时数据
	str, err := net.DownloadStringRetry(url, yahoo.RetryCount(), yahoo.RetryInterval())
	if err != nil {
		return nil, err
	}

	// 解析Json
	quote := &YahooQuote{}
	err = json.Unmarshal([]byte(str), &quote)
	if err != nil {
		return nil, err
	}

	// 校验
	err = yahoo.valid(quote)
	if err != nil {
		return nil, err
	}

	// 解析
	return yahoo.parse(_market, company, date, quote)
}
Exemple #12
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))
}
Exemple #13
0
// EndOf returns the end of the passed unit for the given time.
func EndOf(t time.Time, unit UnitOfTime) time.Time {
	// Retrieve the individual parts of the given time.
	year := t.Year()
	month := t.Month()
	day := t.Day()
	hour := t.Hour()
	minute := t.Minute()
	second := t.Second()
	loc := t.Location()
	// Build new time.
	switch unit {
	case Second:
		return time.Date(year, month, day, hour, minute, second, 999999999, loc)
	case Minute:
		return time.Date(year, month, day, hour, minute, 59, 999999999, loc)
	case Hour:
		return time.Date(year, month, day, hour, 59, 59, 999999999, loc)
	case Day:
		return time.Date(year, month, day, 23, 59, 59, 999999999, loc)
	case Month:
		// Catching leap years makes the month a bit more complex.
		_, nextMonth, _ := t.AddDate(0, 1, 0).Date()
		return time.Date(year, nextMonth, 1, 23, 59, 59, 999999999, loc).AddDate(0, 0, -1)
	case Year:
		return time.Date(year, time.December, 31, 23, 59, 59, 999999999, loc)
	default:
		return t
	}
}
Exemple #14
0
// BeginOf returns the begin of the passed unit for the given time.
func BeginOf(t time.Time, unit UnitOfTime) time.Time {
	// Retrieve the individual parts of the given time.
	year := t.Year()
	month := t.Month()
	day := t.Day()
	hour := t.Hour()
	minute := t.Minute()
	second := t.Second()
	loc := t.Location()
	// Build new time.
	switch unit {
	case Second:
		return time.Date(year, month, day, hour, minute, second, 0, loc)
	case Minute:
		return time.Date(year, month, day, hour, minute, 0, 0, loc)
	case Hour:
		return time.Date(year, month, day, hour, 0, 0, 0, loc)
	case Day:
		return time.Date(year, month, day, 0, 0, 0, 0, loc)
	case Month:
		return time.Date(year, month, 1, 0, 0, 0, 0, loc)
	case Year:
		return time.Date(year, time.January, 1, 0, 0, 0, 0, loc)
	default:
		return t
	}
}
Exemple #15
0
// tApplyRangeMode is the same as applyRangeMode for date/time axis/ranges.
func tApplyRangeMode(mode RangeMode, val time.Time, step TimeDelta, upper bool) (bound time.Time, tic time.Time) {
	if mode.Fixed {
		bound = mode.TValue
		if upper {
			tic = RoundDown(val, step)
		} else {
			tic = RoundUp(val, step)
		}
		return
	}
	if mode.Constrained { // TODO(vodo) use T...
		sval := val.Unix()
		if sval < int64(mode.Lower) {
			sval = int64(mode.Lower)
		} else if sval > int64(mode.Upper) {
			sval = int64(mode.Upper)
		}
		val = time.Unix(sval, 0).In(val.Location())
	}

	switch mode.Expand {
	case ExpandToTic:
		if upper {
			val = RoundUp(val, step)
		} else {
			val = RoundDown(val, step)
		}
		return val, val
	case ExpandNextTic:
		if upper {
			tic = RoundUp(val, step)
		} else {
			tic = RoundDown(val, step)
		}
		s := tic.Unix()
		if math.Abs(float64(s-val.Unix())/float64(step.Seconds())) < 0.15 {
			if upper {
				val = RoundUp(time.Unix(s+step.Seconds()/2, 0).In(val.Location()), step)
			} else {
				val = RoundDown(time.Unix(s-step.Seconds()/2, 0).In(val.Location()), step)
			}
		} else {
			val = tic
		}
		return val, val
	case ExpandABit:
		if upper {
			tic = RoundDown(val, step)
			val = time.Unix(tic.Unix()+step.Seconds()/2, 0).In(val.Location())
		} else {
			tic = RoundUp(val, step)
			val = time.Unix(tic.Unix()-step.Seconds()/2, 0).In(val.Location())
		}
		return

	}

	return val, val
}
Exemple #16
0
func ParseHourAtDay(day time.Time, kitchenString string) (time.Time, error) {
	hourTime, err := time.ParseInLocation(time.Kitchen, kitchenString, time.Local)
	if err != nil {
		return time.Time{}, err
	}
	return time.Date(day.Year(), day.Month(), day.Day(),
		hourTime.Hour(), hourTime.Minute(), hourTime.Second(), 0, day.Location()), nil
}
Exemple #17
0
// Returns whether the date d is before t
func (d Date) BeforeTime(t time.Time) bool {
	// check if equals
	if d.EqualsTime(t) {
		return false
	}
	dtz := d.In(t.Location())
	return t.After(dtz.Add(time.Hour*24 - time.Second))
}
Exemple #18
0
// Returns whether the date d is after t
func (d Date) AfterTime(t time.Time) bool {
	// check if equals
	if d.EqualsTime(t) {
		return false
	}
	dtz := d.In(t.Location())
	return t.Before(dtz)
}
Exemple #19
0
// GetPingKey returns a key for the given ip and time, seconds and nanoseconds are removed
// from pingStartTime in order to group pings by minute
func GetPingKey(ip string, pingStartTime time.Time) []byte {
	keyTimestamp := time.Date(pingStartTime.Year(), pingStartTime.Month(),
		pingStartTime.Day(), pingStartTime.Hour(), pingStartTime.Minute(), 0, 0, pingStartTime.Location())

	key := fmt.Sprintf("%s_%s", ip, keyTimestamp.Format(time.RFC3339))

	return []byte(key)
}
Exemple #20
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())
}
Exemple #21
0
// TimezoneOffsetNoDST returns the timezone offset without the DST component
func TimezoneOffsetNoDST(t time.Time) int {
	_, winterOffset := time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location()).Zone()
	_, summerOffset := time.Date(t.Year(), 7, 1, 0, 0, 0, 0, t.Location()).Zone()
	if winterOffset > summerOffset {
		winterOffset, summerOffset = summerOffset, winterOffset
	}
	return winterOffset
}
Exemple #22
0
func (t *DBTest) TestTypeDate(c *C) {
	src := time.Now().UTC()
	var dst time.Time
	_, err := t.db.QueryOne(pg.LoadInto(&dst), "SELECT ?::date", src)
	c.Assert(err, IsNil)
	c.Assert(dst.Location(), Equals, time.UTC)
	c.Assert(dst.Format("2006-01-02"), Equals, dst.Format("2006-01-02"))
}
Exemple #23
0
// Around computes the sunrise and sunset times for latitude and longitude
// around currentTime. Generally, the computed sunrise will be no earlier
// than 24 hours before currentTime and the computed sunset will be no later
// than 24 hours after currentTime. However, these differences may exceed 24
// hours on days with more than 23 hours of daylight.
// The latitude is positive for north and negative for south. Longitude is
// positive for east and negative for west.
func (s *Sunrise) Around(latitude, longitude float64, currentTime time.Time) {
	s.location = currentTime.Location()
	s.sinLat = sin(latitude)
	s.cosLat = cos(latitude)
	s.jstar = math.Floor(
		julianDay(currentTime.Unix())-0.0009+longitude/360.0+0.5) + 0.0009 - longitude/360.0
	s.computeSolarNoonHourAngle()
}
Exemple #24
0
//returns posts for a certain date
func (md *MongoDB) GetPostsForDate(date time.Time) (posts []BlogPost, err error) {
	date = time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())

	start := date.Unix()
	end := start + (24 * 60 * 60)

	return md.GetPostsForTimespan(start, end, -1)
}
Exemple #25
0
func (y Year) RoundDown(t time.Time) time.Time {
	orig := t.Year()
	rd := y.Num * (orig / y.Num)
	t = time.Date(rd, 1, 1, 0, 0, 0, 0, t.Location())
	// TODO handle shifts in DLS and that
	debug.Printf("Year.RoundDown from %d to %d", orig, rd)
	return t
}
func Greet() {
	var now time.Time = time.Now()
	noon := time.Date(now.Year(), now.Month(), now.Day(), 13, 0, 0, 0, now.Location())
	if now.Before(noon) {
		fmt.Printf("Buongiorno!\n")
	} else {
		fmt.Printf("Buonasera!\n")
	}
}
Exemple #27
0
func SecondsUntilSunriseEvent(currentTime time.Time) int {
	sunTimes := suncalc.SunTimes(currentTime, AUTOLIGHT_LAT, AUTOLIGHT_LONG)
	sunriseTime := sunTimes["dawn"]

	year, month, day := sunriseTime.Date()
	newSunriseTime := time.Date(year, month, day, 2, 30, 0, 0, currentTime.Location())

	return int(math.Ceil(newSunriseTime.Sub(currentTime).Seconds()))
}
Exemple #28
0
func tryAll(str string, rel time.Time, formats []string) (time.Time, bool) {
	for _, f := range formats {
		t, err := time.ParseInLocation(f, str, rel.Location())
		if err == nil {
			return t, true
		}
	}
	return rel, false
}
Exemple #29
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
}
Exemple #30
0
// IsZoneKnown reports whether t is in a known timezone.
// Camlistore uses the magic timezone offset of 1 minute west of UTC
// to mean that the timezone wasn't known.
func IsZoneKnown(t time.Time) bool {
	if t.Location() == UnknownLocation {
		return false
	}
	if _, off := t.Zone(); off == -60 {
		return false
	}
	return true
}