当前位置: 首页>>代码示例>>Golang>>正文


Golang Time.UTC方法代码示例

本文整理汇总了Golang中Time.Time.UTC方法的典型用法代码示例。如果您正苦于以下问题:Golang Time.UTC方法的具体用法?Golang Time.UTC怎么用?Golang Time.UTC使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Time.Time的用法示例。


在下文中一共展示了Time.UTC方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ParseTimeString

// ParseTimeString parses a string into a Unix timestamp. The string may represent an
// absolute time, duration relative to the current time, or a millisecond resolution
// timestamp. All times are converted to UTC.
func ParseTimeString(s string) (int64, error) {
	var (
		t   time.Time
		d   time.Duration
		err error
	)

	// Duration
	d, err = time.ParseDuration(s)

	if err == nil {
		return time.Now().UTC().Add(d).Unix(), nil
	}

	// Parse time.
	for _, layout := range timeLayouts {
		t, err = time.Parse(layout, s)

		if err == nil {
			return t.UTC().Unix(), nil
		}
	}

	// Timestamp; assume this is UTC time.
	i, err := strconv.ParseInt(s, 10, 64)

	if err == nil {
		return i, nil
	}

	return 0, fmt.Errorf("[time] could not parse %s", s)
}
开发者ID:chop-dbhi,项目名称:scds,代码行数:35,代码来源:time.go

示例2: GetUB

func GetUB() *Account {
	uc := &UnitsCounter{
		Direction:   OUTBOUND,
		BalanceType: utils.SMS,
		Balances:    BalanceChain{&Balance{Value: 1}, &Balance{Weight: 20, DestinationIds: "NAT"}, &Balance{Weight: 10, DestinationIds: "RET"}},
	}
	at := &ActionTrigger{
		Id:                    "some_uuid",
		BalanceType:           utils.MONETARY,
		BalanceDirection:      OUTBOUND,
		ThresholdValue:        100.0,
		BalanceDestinationIds: "NAT",
		Weight:                10.0,
		ActionsId:             "Commando",
	}
	var zeroTime time.Time
	zeroTime = zeroTime.UTC() // for deep equal to find location
	ub := &Account{
		Id:             "rif",
		AllowNegative:  true,
		BalanceMap:     map[string]BalanceChain{utils.SMS + OUTBOUND: BalanceChain{&Balance{Value: 14, ExpirationDate: zeroTime}}, utils.DATA + OUTBOUND: BalanceChain{&Balance{Value: 1024, ExpirationDate: zeroTime}}, utils.VOICE: BalanceChain{&Balance{Weight: 20, DestinationIds: "NAT"}, &Balance{Weight: 10, DestinationIds: "RET"}}},
		UnitCounters:   []*UnitsCounter{uc, uc},
		ActionTriggers: ActionTriggers{at, at, at},
	}
	return ub
}
开发者ID:nikbyte,项目名称:cgrates,代码行数:26,代码来源:storage_test.go

示例3: toUTCString

func toUTCString(t time.Time) string {
	utc := t.UTC().Round(time.Second)
	// Ugly but straight forward formatting as time.Parse is such a prima donna
	return fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d.000Z",
		utc.Year(), utc.Month(), utc.Day(),
		utc.Hour(), utc.Minute(), utc.Second())
}
开发者ID:JoeHorn,项目名称:drive,代码行数:7,代码来源:remote.go

示例4: calculateWaitTime

func (s *Stats) calculateWaitTime(d *Download) time.Duration {
	var zeroTime time.Time
	if d.TimeStarted.UTC() == zeroTime.UTC() {
		return s.Clock.Now().Sub(d.TimeRequested)
	}
	return d.TimeStarted.Sub(d.TimeRequested)
}
开发者ID:pombredanne,项目名称:downloaderd-worker,代码行数:7,代码来源:stats.go

示例5: normalizeModTime

func normalizeModTime(modTime time.Time) time.Time {
	// Google Drive supports millisecond resolution for modification time,
	// but some filesystems (e.g., NTFS) support nanosecond resolution.
	// We truncate the modification date to the nearest millisecond to avoid
	// spurious differences when comparing file modification dates.
	return modTime.UTC().Truncate(time.Millisecond)
}
开发者ID:VirtualSatai,项目名称:skicka,代码行数:7,代码来源:skicka.go

示例6: GetIncidentsStartingInRange

func (d *dataAccess) GetIncidentsStartingInRange(start, end time.Time) ([]*models.Incident, error) {
	defer collect.StartTimer("redis", opentsdb.TagSet{"op": "GetIncidentsStartingInRange"})()
	conn := d.GetConnection()
	defer conn.Close()

	ids, err := redis.Ints(conn.Do("ZRANGEBYSCORE", "incidentsByStart", start.UTC().Unix(), end.UTC().Unix()))
	if err != nil {
		return nil, err
	}
	args := make([]interface{}, len(ids)+1)
	args[0] = "incidents"
	for i := range ids {
		args[i+1] = ids[i]
	}
	jsons, err := redis.Strings(conn.Do("HMGET", args...))
	if err != nil {
		return nil, err
	}
	incidents := make([]*models.Incident, len(jsons))
	for i := range jsons {
		inc := &models.Incident{}
		if err = json.Unmarshal([]byte(jsons[i]), inc); err != nil {
			return nil, err
		}
		incidents[i] = inc
	}
	return incidents, nil
}
开发者ID:eswdd,项目名称:bosun,代码行数:28,代码来源:incident_data.go

示例7: download

func download(url, outpath string, pivot time.Time) error {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	if !pivot.IsZero() {
		t := pivot.UTC().Format(http.TimeFormat)
		req.Header.Set("If-Modified-Since", t)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK:
		f, err := os.Create(outpath)
		if err != nil {
			return err
		}
		defer f.Close()
		if _, err := io.Copy(f, resp.Body); err != nil {
			return err
		}

	case http.StatusNotModified:
		return errorNotModified

	default:
		return fmt.Errorf("unexpected response: %s", resp.Status)
	}
	return nil
}
开发者ID:koron,项目名称:upvim,代码行数:34,代码来源:main.go

示例8: JSONStamp

// Convert a time.Time to a JSON timestamp
func JSONStamp(t time.Time) string {
	if !t.IsZero() {
		return t.UTC().Format(JSONLayout)
	}

	return ""
}
开发者ID:pombredanne,项目名称:crate-1,代码行数:8,代码来源:utils.go

示例9: GetCallsInRange

// GetCallsInRange gets an Iterator containing calls in the range [start, end),
// optionally further filtered by data. GetCallsInRange panics if start is not
// before end. Any date filters provided in data will be ignored. If you have
// an end, but don't want to specify a start, use twilio.Epoch for start. If
// you have a start, but don't want to specify an end, use twilio.HeatDeath for
// end.
//
// Assumes that Twilio returns resources in chronological order, latest
// first. If this assumption is incorrect, your results will not be correct.
//
// Returned CallPages will have at most PageSize results, but may have fewer,
// based on filtering.
func (c *CallService) GetCallsInRange(start time.Time, end time.Time, data url.Values) CallPageIterator {
	if start.After(end) {
		panic("start date is after end date")
	}
	d := url.Values{}
	if data != nil {
		for k, v := range data {
			d[k] = v
		}
	}
	d.Del("StartTime")
	d.Del("Page") // just in case
	if start != Epoch {
		startFormat := start.UTC().Format(APISearchLayout)
		d.Set("StartTime>", startFormat)
	}
	if end != HeatDeath {
		// If you specify "StartTime<=YYYY-MM-DD", the *latest* result returned
		// will be midnight (the earliest possible second) on DD. We want all
		// of the results for DD so we need to specify DD+1 in the API.
		//
		// TODO validate midnight-instant math more closely, since I don't think
		// Twilio returns the correct results for that instant.
		endFormat := end.UTC().Add(24 * time.Hour).Format(APISearchLayout)
		d.Set("StartTime<", endFormat)
	}
	iter := NewPageIterator(c.client, d, callsPathPart)
	return &callDateIterator{
		start: start,
		end:   end,
		p:     iter,
	}
}
开发者ID:kevinburke,项目名称:twilio-go,代码行数:45,代码来源:calls.go

示例10: interpretBytesAsTime

func (cursor *Cursor) interpretBytesAsTime(data []byte) time.Time {
	integer := cursor.interpretBytesAsInteger(data)
	var date_time time.Time
	if cursor.mode == IntegerMode {
		if cursor.epoch_unit == SecondsSinceEpoch {
			date_time = cursor.epoch_time.Add(time.Duration(integer) * time.Second)
		} else if cursor.epoch_unit == DaysSinceEpoch {
			date_time = cursor.epoch_time.Add(time.Duration(integer) * 24 * time.Hour)
		}
	} else if cursor.mode == FloatingPointMode {
		var float float64
		if cursor.fp_length == 4 {
			float = float64(math.Float32frombits(uint32(integer)))
		} else {
			float = math.Float64frombits(integer)
		}
		if cursor.epoch_unit == SecondsSinceEpoch {
			date_time = cursor.epoch_time.Add(time.Duration(float * float64(time.Second)))
		} else {
			date_time = cursor.epoch_time.Add(time.Duration(float * 24 * float64(time.Hour)))
		}
	} else {
		date_time = cursor.epoch_time
	}
	return date_time.UTC()
}
开发者ID:modulexcite,项目名称:hecate,代码行数:26,代码来源:cursor.go

示例11: ClearNotificationsBefore

func (d *dataAccess) ClearNotificationsBefore(t time.Time) error {
	conn := d.Get()
	defer conn.Close()

	_, err := conn.Do("ZREMRANGEBYSCORE", pendingNotificationsKey, 0, t.UTC().Unix())
	return slog.Wrap(err)
}
开发者ID:nicollet,项目名称:bosun,代码行数:7,代码来源:notification_data.go

示例12: emit

// Emit a set of stats data points.
func (s *StatsNode) emit(now time.Time) error {
	s.timer.Start()
	point := models.Point{
		Name: "stats",
		Tags: map[string]string{"node": s.en.Name()},
		Time: now.UTC(),
	}
	if s.s.AlignFlag {
		point.Time = point.Time.Round(s.s.Interval)
	}
	stats := s.en.nodeStatsByGroup()
	for group, stat := range stats {
		point.Fields = stat.Fields
		point.Group = group
		point.Dimensions = stat.Dimensions
		point.Tags = stat.Tags
		s.timer.Pause()
		for _, out := range s.outs {
			err := out.CollectPoint(point)
			if err != nil {
				return err
			}
		}
		s.timer.Resume()
	}
	s.timer.Stop()
	return nil
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:29,代码来源:stats.go

示例13: NewPrivateKeySet

func NewPrivateKeySet(keys []*PrivateKey, exp time.Time) *PrivateKeySet {
	return &PrivateKeySet{
		keys:        keys,
		ActiveKeyID: keys[0].ID(),
		expiresAt:   exp.UTC(),
	}
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:7,代码来源:key.go

示例14: NewCA

// NewCA generates a CA certificate/key pair suitable for signing server
// keys for an environment with the given name.
func NewCA(envName string, expiry time.Time) (certPEM, keyPEM string, err error) {
	key, err := rsa.GenerateKey(rand.Reader, KeyBits)
	if err != nil {
		return "", "", err
	}
	now := time.Now()
	template := &x509.Certificate{
		SerialNumber: new(big.Int),
		Subject: pkix.Name{
			CommonName:   fmt.Sprintf("juju-generated CA for environment %q", envName),
			Organization: []string{"juju"},
		},
		NotBefore:             now.UTC().AddDate(0, 0, -7),
		NotAfter:              expiry.UTC(),
		SubjectKeyId:          bigIntHash(key.N),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		IsCA:                  true,
		MaxPathLen:            0, // Disallow delegation for now.
		BasicConstraintsValid: true,
	}
	certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
	if err != nil {
		return "", "", fmt.Errorf("cannot create certificate: %v", err)
	}
	certPEMData := pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certDER,
	})
	keyPEMData := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	})
	return string(certPEMData), string(keyPEMData), nil
}
开发者ID:imoapps,项目名称:juju,代码行数:36,代码来源:cert.go

示例15: formatTs

// 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
}
开发者ID:nvanbenschoten,项目名称:cockroach,代码行数:31,代码来源:types.go


注:本文中的Time.Time.UTC方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。