Esempio n. 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
}
Esempio n. 2
1
// FormatTimestamp formats t into Postgres' text format for timestamps.
func FormatTimestamp(t time.Time) []byte {
	// Need to send dates before 0001 A.D. with " BC" suffix, instead of the
	// minus sign preferred by Go.
	// Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on
	bc := false
	if t.Year() <= 0 {
		// flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11"
		t = t.AddDate((-t.Year())*2+1, 0, 0)
		bc = true
	}
	b := []byte(t.Format(time.RFC3339Nano))

	_, offset := t.Zone()
	offset = offset % 60
	if offset != 0 {
		// RFC3339Nano already printed the minus sign
		if offset < 0 {
			offset = -offset
		}

		b = append(b, ':')
		if offset < 10 {
			b = append(b, '0')
		}
		b = strconv.AppendInt(b, int64(offset), 10)
	}

	if bc {
		b = append(b, " BC"...)
	}
	return b
}
Esempio n. 3
0
// 根据模板文件,json配置生成建表语言,并执行
func creatTbl(ctx *cli.Context) {
	sqlTemp := readSqlTemplate(ctx.String("temp"))
	jsonconf := prod.NewJsonConf(ctx.String("json"))
	for _, conf := range jsonconf.Log_list {
		table := conf.Table
		// 新加的表的建表语句,直接由配置文件生成
		if _, ok := sqlTemp[table]; !ok {
			sqlTemp[table] = createSql(&conf)
			log.Printf("INF: table=%s", table)
		}
	}

	var start time.Time
	var err error
	if ctx.String("milestone") == "" {
		start = time.Now().AddDate(0, 0, 1)
	} else {
		start, err = time.Parse("20060102", ctx.String("milestone"))
		if err != nil {
			log.Panicf("ERR: %s", err)
		}
	}
	days := ctx.Int("days")
	if days < 1 {
		log.Panicf("ERR: arg 'days' invalid, %d", days)
	}
	end := start.AddDate(0, 0, days)

	dates := dateSlice(start, end)
	log.Printf("INF: dates, %s", dates)
	DbExecute(jsonconf, dates, sqlTemp)
}
Esempio n. 4
0
// LoadDescriptorFromDigest takes as input the descriptor directory, a
// descriptor's digest, and the date the digest was created.  It then attempts
// to parse and return the descriptor referenced by the digest.  The descriptor
// directory expects to contain CollecTor server descriptor archives such as:
// server-descriptors-2015-03/
// server-descriptors-2015-04/
// ...
func LoadDescriptorFromDigest(descriptorDir, digest string, date time.Time) (*RouterDescriptor, error) {

	topDir := fmt.Sprintf("server-descriptors-%s", date.Format("2006-01"))
	prevTopDir := fmt.Sprintf("server-descriptors-%s", date.AddDate(0, -1, 0).Format("2006-01"))
	fileName := filepath.Join(descriptorDir, topDir, digest[0:1], digest[1:2], digest)

	// If we cannot find the descriptor file, go one month back in time.
	if _, err := os.Stat(fileName); os.IsNotExist(err) {
		fileName = filepath.Join(descriptorDir, prevTopDir, digest[0:1], digest[1:2], digest)
		if _, err := os.Stat(fileName); os.IsNotExist(err) {
			return nil, fmt.Errorf("Could not find digest file %s in %s", digest, descriptorDir)
		}
	}

	descs, err := ParseDescriptorFile(fileName)
	if err != nil {
		return nil, err
	}

	if descs.Length() != 1 {
		return nil, fmt.Errorf("More than one descriptor in digest file %s.  Bug?", fileName)
	}

	var d *RouterDescriptor
	for _, getDesc := range descs.RouterDescriptors {
		d = getDesc()
		break
	}
	return d, nil
}
Esempio n. 5
0
func (rp *rangeParams) dateArgs() (bool, time.Time, time.Time) {
	var truthy bool = true
	var falsey bool = false
	var t1, t2 time.Time
	var prec string
	if rp.min != nil {
		t1, prec = parseTime(*rp.min, rp.loc)
		switch prec {
		case "day":
			if !*rp.minInclusive {
				// add 1 day and make inclusive
				t1 = t1.AddDate(0, 0, 1)
				rp.minInclusive = &truthy
			}
		default:
			return false, t1, t2
		}
	}
	if rp.max != nil {
		t2, prec = parseTime(*rp.max, rp.loc)
		switch prec {
		case "day":
			if *rp.maxInclusive {
				// add 1 day and change to exclusive
				t2 = t2.AddDate(0, 0, 1)
				rp.maxInclusive = &falsey
			}
		default:
			return false, t1, t2
		}
	}

	return true, t1, t2
}
Esempio n. 6
0
func createDate(str string, now time.Time) time.Time {
	arr := strings.Split(str, "-")
	year, _ := strconv.Atoi(arr[0])
	month, _ := strconv.Atoi(arr[1])
	day, _ := strconv.Atoi(arr[2])
	return now.AddDate(year-now.Year(), month-int(now.Month()), day-now.Day())
}
Esempio n. 7
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
	}
}
Esempio n. 8
0
// 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]
}
Esempio n. 9
0
func startOfNextMonth(original time.Time) time.Time {
	next := original.AddDate(0, 1, -original.Day()+1) // the first of the next month
	clockTimeToRemove := time.Duration(original.Hour()) * time.Hour
	clockTimeToRemove += time.Duration(original.Minute()) * time.Minute
	clockTimeToRemove += time.Duration(original.Second()) * time.Second
	return next.Add(-clockTimeToRemove)
}
Esempio n. 10
0
func (oc OffsetContext) offset(origin time.Time) (time.Time, error) {
	var days, months, years int

	switch oc.interval {
	case INTERVAL_WEEK:
		days = oc.count * 7
	case INTERVAL_DAY:
		days = oc.count
	case INTERVAL_MONTH:
		months = oc.count
	case INTERVAL_YEAR:
		years = oc.count
	}

	var direction int
	switch oc.direction {
	case DIRECTION_LEFT:
		direction = -1
	case DIRECTION_RIGHT:
		direction = 1
	case DIRECTION_CURRENT:
		direction = 0
	}

	d := origin.AddDate(direction*years, direction*months, direction*days)
	return d, nil
}
Esempio n. 11
0
// WorkdayN reports the day of the month that corresponds to the nth workday
// for the given year and 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 0.
//   n < 0: counting begins at the end of the month.
func (c *Calendar) WorkdayN(year int, month time.Month, n int) int {
	var date time.Time
	var add int
	if n == 0 {
		return 0
	}

	if n > 0 {
		date = time.Date(year, month, 1, 12, 0, 0, 0, time.UTC)
		add = 1
	} else {
		date = time.Date(year, month+1, 1, 12, 0, 0, 0, time.UTC).AddDate(0, 0, -1)
		add = -1
		n = -n
	}

	ndays := 0
	for ; month == date.Month(); date = date.AddDate(0, 0, add) {
		if c.IsWorkday(date) {
			ndays++
			if ndays == n {
				return date.Day()
			}
		}
	}
	return 0
}
Esempio n. 12
0
// WriteFormattedTime formats t into a format postgres understands.
// Taken with gratitude from pq: https://github.com/lib/pq/blob/b269bd035a727d6c1081f76e7a239a1b00674c40/encode.go#L403
func (pd *Postgres) WriteFormattedTime(buf common.BufferWriter, t time.Time) {
	buf.WriteRune('\'')
	defer buf.WriteRune('\'')
	// XXX: This doesn't currently deal with infinity values

	// Need to send dates before 0001 A.D. with " BC" suffix, instead of the
	// minus sign preferred by Go.
	// Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on
	bc := false
	if t.Year() <= 0 {
		// flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11"
		t = t.AddDate((-t.Year())*2+1, 0, 0)
		bc = true
	}
	buf.WriteString(t.Format(time.RFC3339Nano))

	_, offset := t.Zone()
	offset = offset % 60
	if offset != 0 {
		// RFC3339Nano already printed the minus sign
		if offset < 0 {
			offset = -offset
		}

		buf.WriteRune(':')
		if offset < 10 {
			buf.WriteRune('0')
		}
		buf.WriteString(strconv.FormatInt(int64(offset), 10))
	}

	if bc {
		buf.WriteString(" BC")
	}
}
Esempio n. 13
0
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
}
Esempio n. 14
0
func (b *BaseData) CleanData(t time.Time) {
	daysAgo20 := t.AddDate(0, 0, -20)
	err := db.Remove(DB, C_REQUEST, bson.M{"time": bson.M{"$lt": daysAgo20}})
	if err != nil && !strings.Contains(err.Error(), "not found") {
		log.Error(err)
	}
}
Esempio n. 15
0
func startOfNextDay(original time.Time) time.Time {
	next := original.AddDate(0, 0, 1)
	clockTimeToRemove := time.Duration(original.Hour()) * time.Hour
	clockTimeToRemove += time.Duration(original.Minute()) * time.Minute
	clockTimeToRemove += time.Duration(original.Second()) * time.Second
	return next.Add(-clockTimeToRemove)
}
Esempio n. 16
0
func parseDates(validFrom, validFor *string) (*time.Time, *time.Time, error) {
	var notBefore, notAfter time.Time
	var err error
	if len(*validFrom) == 0 {
		notBefore = time.Now()
	} else {
		notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom)
		if err != nil {
			return nil, nil, fmt.Errorf("Could not parse 'from' date")
		}
	}
	m := regexp.MustCompile(`^(\d+)([ydhm])$`).FindStringSubmatch(*validFor)
	if m == nil {
		return nil, nil, fmt.Errorf("Could not parse 'period'")
	}
	n, err := strconv.Atoi(m[1])
	if err != nil {
		return nil, nil, fmt.Errorf("Could not parse 'period' unit")
	}
	switch m[2] {
	case "y":
		notAfter = notBefore.AddDate(n, 0, 0)
	case "d":
		notAfter = notBefore.AddDate(0, 0, n)
	case "h":
		notAfter = notBefore.Add(time.Hour * time.Duration(n))
	case "m":
		notAfter = notBefore.Add(time.Minute * time.Duration(n))
	}

	return &notBefore, &notAfter, nil
}
Esempio n. 17
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
}
Esempio n. 18
0
func getDateBoundaries(per Period, start, end time.Time) []time.Time {
	var incMonth, incYear int
	var periodStart time.Time

	switch per {
	case PeriodMonth:
		incMonth = 1
		periodStart = time.Date(start.Year(), start.Month(), 1, 0, 0, 0, 0, time.UTC)
	case PeriodQuarter:
		incMonth = 3
		switch start.Month() {
		case time.January, time.February, time.March:
			periodStart = time.Date(start.Year(), time.January, 1, 0, 0, 0, 0, time.UTC)
		case time.April, time.May, time.June:
			periodStart = time.Date(start.Year(), time.April, 1, 0, 0, 0, 0, time.UTC)
		case time.July, time.August, time.September:
			periodStart = time.Date(start.Year(), time.July, 1, 0, 0, 0, 0, time.UTC)
		default:
			periodStart = time.Date(start.Year(), time.October, 1, 0, 0, 0, 0, time.UTC)
		}
	case PeriodYear:
		incYear = 1
		periodStart = time.Date(start.Year(), time.January, 1, 0, 0, 0, 0, time.UTC)
	}

	boundaries := []time.Time{periodStart}
	for periodStart.Before(end) {
		periodStart = periodStart.AddDate(incYear, incMonth, 0)
		boundaries = append(boundaries, periodStart)
	}

	return boundaries
}
Esempio n. 19
0
// formatTs formats t with an optional offset into a format lib/pq understands,
// appending to the provided tmp buffer and reallocating if needed. The function
// will then return the resulting buffer. formatTs is mostly cribbed from
// github.com/lib/pq.
func formatTs(t time.Time, offset *time.Location, tmp []byte) (b []byte) {
	// Need to send dates before 0001 A.D. with " BC" suffix, instead of the
	// minus sign preferred by Go.
	// Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on
	if offset != nil {
		t = t.In(offset)
	} else {
		t = t.UTC()
	}
	bc := false
	if t.Year() <= 0 {
		// flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11"
		t = t.AddDate((-t.Year())*2+1, 0, 0)
		bc = true
	}

	if offset != nil {
		b = t.AppendFormat(tmp, pgTimeStampFormat)
	} else {
		b = t.AppendFormat(tmp, pgTimeStampFormatNoOffset)
	}

	if bc {
		b = append(b, " BC"...)
	}
	return b
}
Esempio n. 20
0
// FirstOfTheMonth returns a date that occurs on the first of the month of the
// supplied date. For example, if the supplied date is 6/13/2015 then this function
// would return 6/1/2015 (at the same time as the former)
func FirstOfTheMonth(d time.Time) time.Time {
	if d.IsZero() {
		return d
	}

	day := d.Day()
	return d.AddDate(0, 0, 1-day)
}
Esempio n. 21
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())
}
Esempio n. 22
0
func adjustSunsetDate(sunset *time.Time, sunrise *time.Time) *time.Time {
	if sunset == nil || sunrise == nil || sunrise.Before(*sunset) {
		return sunset
	}

	temp := sunset.AddDate(0, 0, 1)
	return &temp
}
Esempio n. 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
}
Esempio n. 24
0
// durationToNextDay 现在到明天0点的时间间隔
func (mr marketRecorder) durationToNextDay(now time.Time) time.Duration {

	year, month, day := now.AddDate(0, 0, 1).Date()

	// 市场所处时区的下一个0点
	marketTomorrowZero := time.Date(year, month, day, 0, 0, 0, 0, now.Location())

	return marketTomorrowZero.Sub(now)
}
Esempio n. 25
0
// Next conforms to the Schedule interface but this kind of jobs
// doesn't need to be run more than once, so it doesn't return a new date but the existing one.
func (schedule SimpleSchedule) Next(t time.Time) time.Time {
	// If the date set is after the reference time return it
	// if it's before, return a virtually infinite sleep date
	// so do nothing.
	if schedule.Date.After(t) {
		return schedule.Date
	}
	return t.AddDate(10, 0, 0)
}
Esempio n. 26
0
// countWorkdays reports the number of workdays from the given date to the end
// of the month.
func (c *Calendar) countWorkdays(dt time.Time, month time.Month) int {
	n := 0
	for ; month == dt.Month(); dt = dt.AddDate(0, 0, 1) {
		if c.IsWorkday(dt) {
			n++
		}
	}
	return n
}
Esempio n. 27
0
// Applies the lexer's relative offset to the provided base time.
func (l *dateLexer) resolveOffset(rel time.Time) time.Time {
	rel = rel.AddDate(l.offsets[O_YEAR], l.offsets[O_MONTH], l.offsets[O_DAY])
	rel = rel.Add(time.Hour*time.Duration(l.offsets[O_HOUR]) +
		time.Minute*time.Duration(l.offsets[O_MIN]) +
		time.Second*time.Duration(l.offsets[O_SEC]))
	if DEBUG {
		fmt.Printf("Parsed offset as %s %s\n", rel.Weekday(), rel)
	}
	return rel
}
Esempio n. 28
0
// endday - 最后日期
// lastNDays - 从endday往前数N天。
func datekeys(lastNDays int, endday time.Time) []string {
	t := endday.AddDate(0, 0, -lastNDays+1)
	// t := time.Now().AddDate(0, 0, -lastNDays+1)
	result := []string{}
	for i := 0; i < lastNDays; i++ {
		result = append(result, t.AddDate(0, 0, i).Format("2006-01-02"))
	}

	return result
}
Esempio n. 29
0
func printJournalHeader(xprop *XBusiness, d1, d2 *time.Time /*, ra *RentalAgreement, x *XPerson, xu *XUnit*/) {
	// fmt.Printf("         1         2         3         4         5         6         7         8\n")
	// fmt.Printf("12345678901234567890123456789012345678901234567890123456789012345678901234567890\n")
	printJReportDoubleLine()
	fmt.Printf("   Business:  %-13s\n", xprop.P.Name)
	fmt.Printf("   %s - %s\n", d1.Format(RRDATEFMT), d2.AddDate(0, 0, -1).Format(RRDATEFMT))
	printJReportLine()
	fmt.Printf(jfmt.Hdr, "Description", "Date", "RntAgr", "Rentable", "GL No", "Amount")
	printJReportLine()
}
Esempio n. 30
0
// isSemiHoliday returns true if it is American Holiday Eve,
// or the day after Thanksgiving day.
func isSemiHoliday(t time.Time) (string, bool) {
	// the day after Thanksgiving Day
	st, _ := isUSHoliday(t.AddDate(0, 0, -1))
	if st == "Thanksgiving Day" {
		return "Day After Thanksgiving Day", true
	}
	tm := t.AddDate(0, 0, 1)
	sh, bl := isUSHoliday(tm)
	return "Before " + sh, bl
}