本文整理匯總了Golang中Time.Time.Round方法的典型用法代碼示例。如果您正苦於以下問題:Golang Time.Round方法的具體用法?Golang Time.Round怎麽用?Golang Time.Round使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Time.Time
的用法示例。
在下文中一共展示了Time.Round方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: RemoveTargetsWithExpires
// If paths is empty, all targets will be removed.
func (r *Repo) RemoveTargetsWithExpires(paths []string, expires time.Time) error {
if !validExpires(expires) {
return ErrInvalidExpires{expires}
}
t, err := r.targets()
if err != nil {
return err
}
if len(paths) == 0 {
t.Targets = make(data.Files)
} else {
removed := false
for _, path := range paths {
path = util.NormalizeTarget(path)
if _, ok := t.Targets[path]; !ok {
continue
}
removed = true
delete(t.Targets, path)
}
if !removed {
return nil
}
}
t.Expires = expires.Round(time.Second)
t.Version++
return r.setMeta("targets.json", t)
}
示例2: writeTimestamp
func writeTimestamp(w io.Writer, t time.Time) (err error) {
nanoSeconds := t.Round(time.Microsecond).UnixNano()
if t.IsZero() {
return writeLong(w, math.MinInt64)
}
return writeLong(w, nanoSeconds/int64(time.Microsecond))
}
示例3: RoundTimeUp
// RoundTimeUp rounds the time to the next second/minute/hours depending on the duration
func RoundTimeUp(realTime time.Time, duration time.Duration) time.Time {
tmpTime := realTime.Round(duration)
if tmpTime.Before(realTime) {
return tmpTime.Add(duration)
}
return tmpTime
}
示例4: GenKeyWithExpires
func (r *Repo) GenKeyWithExpires(keyRole string, expires time.Time) (string, error) {
if !keys.ValidRole(keyRole) {
return "", ErrInvalidRole{keyRole}
}
if !validExpires(expires) {
return "", ErrInvalidExpires{expires}
}
root, err := r.root()
if err != nil {
return "", err
}
key, err := keys.NewKey()
if err != nil {
return "", err
}
if err := r.local.SaveKey(keyRole, key.SerializePrivate()); err != nil {
return "", err
}
role, ok := root.Roles[keyRole]
if !ok {
role = &data.Role{KeyIDs: []string{}, Threshold: 1}
root.Roles[keyRole] = role
}
role.KeyIDs = append(role.KeyIDs, key.ID)
root.Keys[key.ID] = key.Serialize()
root.Expires = expires.Round(time.Second)
root.Version++
return key.ID, r.setMeta("root.json", root)
}
示例5: cronHandler
// cronHandler is called by app engine cron to check for work
// and also called by task queue invocations to run the work for
// a specific registered functions.
func cronHandler(ctxt appengine.Context, w http.ResponseWriter, req *http.Request) {
cron.RLock()
list := cron.list
cron.RUnlock()
force := req.FormValue("force") == "1"
// We're being called by app engine master cron,
// so look for new work to queue in tasks.
now := time.Now()
var old time.Time
err := Transaction(ctxt, func(ctxt appengine.Context) error {
if err := ReadMeta(ctxt, "app.cron.time", &old); err != nil && err != datastore.ErrNoSuchEntity {
return err
}
if !old.Before(now) {
return nil
}
return WriteMeta(ctxt, "app.cron.time", now)
})
if err != nil { // already logged
return
}
ctxt.Infof("cron %v -> %v", old, now)
for _, cr := range list {
if now.Round(cr.dt) != old.Round(cr.dt) || force {
ctxt.Infof("start cron %s", cr.name)
Task(ctxt, "app.cron."+cr.name, "cron", cr.name)
}
}
}
示例6: RoundFrac
// RoundFrac rounds fractional seconds precision with new fsp and returns a new one.
// We will use the “round half up” rule, e.g, >= 0.5 -> 1, < 0.5 -> 0,
// so 2011:11:11 10:10:10.888888 round 0 -> 2011:11:11 10:10:11
// and 2011:11:11 10:10:10.111111 round 0 -> 2011:11:11 10:10:10
func RoundFrac(t gotime.Time, fsp int) (gotime.Time, error) {
_, err := checkFsp(fsp)
if err != nil {
return t, errors.Trace(err)
}
return t.Round(gotime.Duration(math.Pow10(9-fsp)) * gotime.Nanosecond), nil
}
示例7: SnapshotWithExpires
func (r *Repo) SnapshotWithExpires(t CompressionType, expires time.Time) error {
if !validExpires(expires) {
return ErrInvalidExpires{expires}
}
snapshot, err := r.snapshot()
if err != nil {
return err
}
db, err := r.db()
if err != nil {
return err
}
// TODO: generate compressed manifests
for _, name := range snapshotManifests {
if err := r.verifySignature(name, db); err != nil {
return err
}
var err error
snapshot.Meta[name], err = r.fileMeta(name)
if err != nil {
return err
}
}
snapshot.Expires = expires.Round(time.Second)
snapshot.Version++
return r.setMeta("snapshot.json", snapshot)
}
示例8: getContainerMetrics
func (self *defaultDecoder) getContainerMetrics(container *source_api.Container, labels map[string]string) []sinksV1Api.Timeseries {
if container == nil {
return nil
}
labels[sinksV1Api.LabelContainerName.Key] = container.Name
// One metric value per data point.
var result []sinksV1Api.Timeseries
labelsAsString := util.LabelsToString(labels, ",")
for _, stat := range container.Stats {
if stat == nil {
continue
}
// Add all supported metrics that have values.
for index, supported := range self.supportedStatMetrics {
// Finest allowed granularity is seconds.
stat.Timestamp = stat.Timestamp.Round(time.Second)
key := timeseriesKey{
Name: supported.Name,
Labels: labelsAsString,
}
// TODO: remove this once the heapster source is tested to not provide duplicate stats.
if data, ok := self.lastExported[key]; ok && data.After(stat.Timestamp) {
continue
}
if supported.HasValue(&container.Spec) {
// Cumulative stats have container creation time as their start time.
var startTime time.Time
if supported.Type == sinksV1Api.MetricCumulative {
startTime = container.Spec.CreationTime
} else {
startTime = stat.Timestamp
}
points := supported.GetValue(&container.Spec, stat)
for _, point := range points {
labels := util.CopyLabels(labels)
for name, value := range point.Labels {
labels[name] = value
}
timeseries := sinksV1Api.Timeseries{
MetricDescriptor: &self.supportedStatMetrics[index].MetricDescriptor,
Point: &sinksV1Api.Point{
Name: supported.Name,
Labels: labels,
Start: startTime.Round(time.Second),
End: stat.Timestamp,
Value: point.Value,
},
}
result = append(result, timeseries)
}
}
self.lastExported[key] = stat.Timestamp
}
}
return result
}
示例9: nextTimeBoundary
// nextTimeBoundary returns the time when the currently open time window closes.
func nextTimeBoundary(baseTime time.Time, windowSize time.Duration) time.Time {
// This will round down before the halfway point.
b := baseTime.Round(windowSize)
if b.Before(baseTime) {
// It was rounded down, adjust up to next boundary.
b = b.Add(windowSize)
}
return b
}
示例10: getTime
func (ac accumulator) getTime(t []time.Time) time.Time {
var timestamp time.Time
if len(t) > 0 {
timestamp = t[0]
} else {
timestamp = time.Now()
}
return timestamp.Round(ac.precision)
}
示例11: stratificationBoundary
// Get the closest time before or equal to <t> that is an integer multiple of
// <period>.
func stratificationBoundary(t time.Time, period time.Duration) time.Time {
return t.Round(period)
/*secsSinceEpoch := t.Unix()
// TODO: Is it safe to use Unix for this? Will leap seconds screw us up?
periodSecs := int64(period)/int64(time.Second)
// Round down to nearest stratification
boundarySecsSinceEpoch := secsSinceEpoch - (secsSinceEpoch % periodSecs)
return time.Unix(boundarySecsSinceEpoch)*/
}
示例12: Delay
// The number of time units returned represents
// the processing time accumulated within l2met.
// E.g. If the resolution of the bucket/id is 60s
// and the delay is 2, then it took 120s for l2met
// to process the bucket.
func (id *Id) Delay(t time.Time) int64 {
t0 := id.Time.Round(id.Resolution).Unix()
t1 := t.Round(id.Resolution).Unix()
base := id.Resolution / time.Second
if base != 0 {
return (t1 - t0) / int64(base)
}
return 0
}
示例13: stateIdx
func stateIdx(t time.Time) int {
t = t.Round(durPrTick)
a := time.Duration(t.Hour()) * time.Hour
a += time.Duration(t.Minute()) * time.Minute
a += time.Duration(t.Second()) * time.Second
return int(a / durPrTick)
}
示例14: insertNum
func insertNum(t *testing.T, conn *sql.Tx,
small int, bigint string,
notint float64, bigreal string,
text string, date time.Time,
) bool {
date = date.Round(time.Second)
qry := fmt.Sprintf(`INSERT INTO `+tbl+`
(F_int, F_bigint, F_real, F_bigreal, F_text, F_date)
VALUES (%d, %s, %3.3f, %s, '%s', TO_DATE('%s', 'YYYY-MM-DD HH24:MI:SS'))
`, small, bigint, notint, bigreal, text, date.Format("2006-01-02 15:04:05"))
if _, err := conn.Exec(qry); err != nil {
t.Errorf("cannot insert into "+tbl+" (%q): %v", qry, err)
return false
}
row := conn.QueryRow("SELECT F_int, F_bigint, F_real, F_bigreal, F_text, F_date FROM "+tbl+" WHERE F_int = :1", small)
var (
smallO int
bigintO big.Int
notintO float64
bigrealF, bigrealO big.Rat
bigintS, bigrealS string
textO string
dateO time.Time
)
if err := row.Scan(&smallO, &bigintS, ¬intO, &bigrealS, &textO, &dateO); err != nil {
t.Errorf("error scanning row[%d]: %v", small, errgo.Details(err))
return false
}
t.Logf("row: small=%d big=%s notint=%f bigreal=%s text=%q date=%s",
smallO, bigintS, notintO, bigrealS, textO, dateO)
if smallO != small {
t.Errorf("small mismatch: got %d, awaited %d.", smallO, small)
}
(&bigintO).SetString(bigintS, 10)
if bigintO.String() != bigint {
t.Errorf("bigint mismatch: got %s, awaited %s.", bigintO, bigint)
}
if notintO != notint {
t.Errorf("noting mismatch: got %f, awaited %f.", notintO, notint)
}
(&bigrealF).SetString(bigreal)
(&bigrealO).SetString(bigrealS)
if (&bigrealO).Cmp(&bigrealF) != 0 {
t.Errorf("bigreal mismatch: got %s, awaited %f.", (&bigrealO), (&bigrealF))
}
if textO != text {
t.Errorf("text mismatch: got %q, awaited %q.", textO, text)
}
if !dateO.Equal(date) {
t.Errorf("date mismatch: got %s, awaited %s.", dateO, date.Round(time.Second))
}
return true
}
示例15: SetStartEnd
// SetStartEnd sets the start date and the end date of an Usage
func (u *Usage) SetStartEnd(start, end time.Time) error {
roundedStart := start.Round(u.Object.UsageGranularity)
if roundedStart.After(start) {
roundedStart = roundedStart.Add(-u.Object.UsageGranularity)
}
roundedEnd := end.Round(u.Object.UsageGranularity)
if roundedEnd.Before(end) {
roundedEnd = roundedEnd.Add(u.Object.UsageGranularity)
}
return u.SetDuration(roundedEnd.Sub(roundedStart))
}