本文整理汇总了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)
}
示例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
}
示例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())
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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 ""
}
示例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,
}
}
示例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()
}
示例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)
}
示例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
}
示例13: NewPrivateKeySet
func NewPrivateKeySet(keys []*PrivateKey, exp time.Time) *PrivateKeySet {
return &PrivateKeySet{
keys: keys,
ActiveKeyID: keys[0].ID(),
expiresAt: exp.UTC(),
}
}
示例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
}
示例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
}