本文整理汇总了Golang中Time.Time.Format方法的典型用法代码示例。如果您正苦于以下问题:Golang Time.Format方法的具体用法?Golang Time.Format怎么用?Golang Time.Format使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Time.Time
的用法示例。
在下文中一共展示了Time.Format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: FormatTimestamp
// 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
}
示例2: getTouchCmd
func getTouchCmd(path string, mtime time.Time) string {
return fmt.Sprintf(
`call touch -d "%s" "%s"`,
mtime.Format(mtimeFormat),
path,
)
}
示例3: buildCommonLogLine
// buildCommonLogLine builds a log entry for req in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size.
func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
username := "-"
if url.User != nil {
if name := url.User.Username(); name != "" {
username = name
}
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
uri := url.RequestURI()
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
buf = append(buf, host...)
buf = append(buf, " - "...)
buf = append(buf, username...)
buf = append(buf, " ["...)
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
buf = append(buf, `] "`...)
buf = append(buf, req.Method...)
buf = append(buf, " "...)
buf = appendQuoted(buf, uri)
buf = append(buf, " "...)
buf = append(buf, req.Proto...)
buf = append(buf, `" `...)
buf = append(buf, strconv.Itoa(status)...)
buf = append(buf, " "...)
buf = append(buf, strconv.Itoa(size)...)
return buf
}
示例4: printDay
func (fs *fileStorage) printDay(t time.Time) {
if fs.day == t.Day() {
return
}
fs.day = t.Day()
fs.logw.Write([]byte("=============== " + t.Format("Jan 2, 2006 (MST)") + " ===============\n"))
}
示例5: sign
func (k *Keys) sign(s *Service, t time.Time) []byte {
h := ghmac([]byte("AWS4"+k.SecretKey), []byte(t.Format(iSO8601BasicFormatShort)))
h = ghmac(h, []byte(s.Region))
h = ghmac(h, []byte(s.Name))
h = ghmac(h, []byte("aws4_request"))
return h
}
示例6: Trace
func (t *traceWriter) Trace(traceId []byte) {
var (
coordinator string
duration int
)
t.session.Query(`SELECT coordinator, duration
FROM system_traces.sessions
WHERE session_id = ?`, traceId).
Consistency(One).Scan(&coordinator, &duration)
iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
FROM system_traces.events
WHERE session_id = ?`, traceId).
Consistency(One).Iter()
var (
timestamp time.Time
activity string
source string
elapsed int
)
t.mu.Lock()
defer t.mu.Unlock()
fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
traceId, coordinator, time.Duration(duration)*time.Microsecond)
for iter.Scan(×tamp, &activity, &source, &elapsed) {
fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
}
if err := iter.Close(); err != nil {
fmt.Fprintln(t.w, "Error:", err)
}
}
示例7: retrieveChangeSets
func (p *InMemoryDataStore) retrieveChangeSets(dsocialId string, after time.Time) ([]*dm.ChangeSet, bc.NextToken, error) {
l := list.New()
var afterString string
if !after.IsZero() {
afterString = after.Format(dm.UTC_DATETIME_FORMAT)
}
for _, v := range p.retrieveChangesetCollection().Data {
if cs, ok := v.(*dm.ChangeSet); ok {
if cs.RecordId == dsocialId {
if after.IsZero() || cs.CreatedAt > afterString {
cs2 := new(dm.ChangeSet)
*cs2 = *cs
l.PushBack(cs2)
}
}
}
}
rc := make([]*dm.ChangeSet, l.Len())
for i, iter := 0, l.Front(); iter != nil; i, iter = i+1, iter.Next() {
if iter.Value != nil {
rc[i] = iter.Value.(*dm.ChangeSet)
}
}
return rc, nil, nil
}
示例8: GetStats
// GetStats returns a basic set of statistics for different events.
// Events start at the given start date, if one is provided.
// If not, this function will consider all stated events dating to the creation of the sending domain.
func (m *MailgunImpl) GetStats(limit int, skip int, startDate *time.Time, event ...string) (int, []Stat, error) {
r := simplehttp.NewHTTPRequest(generateApiUrl(m, statsEndpoint))
if limit != -1 {
r.AddParameter("limit", strconv.Itoa(limit))
}
if skip != -1 {
r.AddParameter("skip", strconv.Itoa(skip))
}
if startDate != nil {
r.AddParameter("start-date", startDate.Format(time.RFC3339))
}
for _, e := range event {
r.AddParameter("event", e)
}
r.SetBasicAuth(basicAuthUser, m.ApiKey())
var res statsEnvelope
err := getResponseFromJSON(r, &res)
if err != nil {
return -1, nil, err
} else {
return res.TotalCount, res.Items, nil
}
}
示例9: GetTasks
func GetTasks(status string) []types.Task {
var task []types.Task
var TaskId int
var TaskTitle string
var TaskContent string
var TaskCreated time.Time
var getTasksql string
if status == "pending" {
getTasksql = "select id, title, content, created_date from task where finish_date is null and is_deleted='N' order by created_date asc"
} else if status == "trashed" {
getTasksql = "select id, title, content, created_date from task where is_deleted='Y' order by created_date asc"
} else if status == "complete" {
getTasksql = "select id, title, content, created_date from task where finish_date is not null order by created_date asc"
}
rows, err := database.Query(getTasksql)
if err != nil {
fmt.Println(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&TaskId, &TaskTitle, &TaskContent, &TaskCreated)
if err != nil {
fmt.Println(err)
}
TaskCreated = TaskCreated.Local()
a := types.Task{Id: TaskId, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20]}
task = append(task, a)
}
return task
}
示例10: formatTime
func formatTime(t time.Time) string {
s := time.Since(t)
switch {
case s.Seconds() < 60:
f := "second"
if math.Floor(s.Seconds()) > 1 {
f += "s"
}
return fmt.Sprintf("%d "+f+" ago", int(s.Seconds()))
case s.Minutes() < 60:
f := "minute"
if math.Floor(s.Minutes()) > 1 {
f += "s"
}
return fmt.Sprintf("%d "+f+" ago", int(s.Minutes()))
case s.Hours() < 24:
f := "hour"
if math.Floor(s.Hours()) > 1 {
f += "s"
}
return fmt.Sprintf("%d "+f+" ago", int(s.Hours()))
default:
layout := "Jan 2, 2006 at 3:04pm (MST)"
return t.Format(layout)
}
}
示例11: ExportVariablesWithTimestamp
// Export expvars to Cube right now. Use the provided timestamp for the
// submitted event. This function sends variables once and returns.
//
// You shouldn't need this function under normal circumstances. Use Run()
// instead.
func ExportVariablesWithTimestamp(collectionType string, putUrl string, timestamp time.Time) error {
variables := make([]string, 0)
expvar.Do(func(entry expvar.KeyValue) {
variables = append(variables, fmt.Sprintf("%q: %s", entry.Key, entry.Value))
})
request := fmt.Sprintf(
`[
{
"type": "%s",
"time": "%s",
"data": { %s }
}
]`,
collectionType,
timestamp.Format(time.ANSIC),
strings.Join(variables, ","))
response, err := http.Post(putUrl, "application/json", bytes.NewBufferString(request))
if err != nil {
log.Printf("Error POSTing events to Cube collector: %v", err)
log.Printf("The request we tried to post: %v", request)
return err
}
defer response.Body.Close()
return nil
}
示例12: rotateFile
// rotateFile closes the syncBuffer's file and starts a new one.
func (sb *syncBuffer) rotateFile(now time.Time) error {
if sb.file != nil {
if err := sb.Flush(); err != nil {
return err
}
if err := sb.file.Close(); err != nil {
return err
}
}
var err error
sb.file, _, err = create(sb.sev, now)
sb.nbytes = 0
if err != nil {
return err
}
sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
// Write header.
var buf bytes.Buffer
fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
fmt.Fprintf(&buf, "Running on machine: %s\n", host)
fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
fmt.Fprintf(&buf, "Log line format: [IWEF]yymmdd hh:mm:ss.uuuuuu file:line msg\n")
var n int
n, err = sb.file.Write(buf.Bytes())
sb.nbytes += uint64(n)
return err
}
示例13: buildLogLine
// buildLogLine creates a common log format
// in addition to the common fields, we also append referrer, user agent,
// request ID and response time (microseconds)
// ie, in apache mod_log_config terms:
// %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" %L %D
func buildLogLine(l *responseLogger, r *http.Request, start time.Time) string {
redactPassword(r)
username := parseUsername(r)
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
uri := r.URL.RequestURI()
referer := r.Referer()
userAgent := r.UserAgent()
return fmt.Sprintf(`%s - %s [%s] "%s %s %s" %s %s "%s" "%s" %s %d`,
host,
detect(username, "-"),
start.Format("02/Jan/2006:15:04:05 -0700"),
r.Method,
uri,
r.Proto,
detect(strconv.Itoa(l.Status()), "-"),
strconv.Itoa(l.Size()),
detect(referer, "-"),
detect(userAgent, "-"),
r.Header.Get("Request-Id"),
// response time, report in microseconds because this is consistent
// with apache's %D parameter in mod_log_config
int64(time.Since(start)/time.Microsecond))
}
示例14: addToFile
// adds the time <t> plus the string <url> to the url-file
func (q *AltPlugin) addToFile(url string, t time.Time) {
line := fmt.Sprintf("%v %v", t.Format(q.ic.GetStringOption("Altbot", "timeformat")), url)
err := q.writeLine(q.ic.GetStringOption("Altbot", "file"), line)
if err != nil {
log.Println(err)
}
}
示例15: createLogFile
// createLogFile 创建日志文件
func (this *FileWriter) createLogFile(date time.Time) error {
var day = date.Day()
if day == this.day {
//文件无需更新
return nil
}
//关闭原来的日志文件,并创建新的日志文件
if this.file != nil {
err := this.file.Close()
if err != nil {
return err
}
}
//创建新的日志文件
var dir = date.Format("200601")
var path = filepath.Join(this.path, dir)
var err = os.MkdirAll(path, 0770)
if err != nil {
return err
}
var fileName = date.Format("20060102") + ".log"
var filePath = filepath.Join(path, fileName)
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0660)
if err != nil && !os.IsExist(err) {
return err
}
this.file = file
this.writer = bufio.NewWriter(file)
return nil
}