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


Golang Time.String方法代码示例

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


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

示例1: queryFixer

// query Flickr to detect a search range that will give us the amount of images we need for the mosaic
func queryFixer(fg HttpGetter, startDate time.Time, endDate time.Time, resultsNeeded int, query string, called int) (time.Time, string) {
	var goodStart time.Time
	resultCountQuery := "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=488c1e7018f1ddf78b09d51a9604622a&media=photos&per_page=400&page=1&format=json&nojsoncallback=1&min_upload_date=" + strconv.FormatInt(startDate.Unix(), 10) + "&max_upload_date=" + strconv.FormatInt(endDate.Unix(), 10) + "&text=" + query + "&sort=relevance"
	body, err := fg.Get(resultCountQuery)
	if err != nil {
		logger.Println("error getting Flickr photo list: ", err)
	}

	var flickrResp PhotoQueryEnv
	err = json.Unmarshal(body, &flickrResp)
	if err != nil {
		logger.Println("error unmarshaling JSON: ", err)
	}
	resultCount, err := strconv.Atoi(flickrResp.Photos.Total)
	if err != nil {
		logger.Println("error converting result to int: ", err)
	}
	//TODO: lame, should really have a better way to stop this from looping forever
	if resultsNeeded > resultCount && called < 100 {
		newStart := startDate.Add(-(time.Hour * 168 * 2))
		return queryFixer(fg, newStart, endDate, resultsNeeded, query, called+1)
	}
	logger.Println("returning: ", startDate.String())
	goodStart = startDate
	return goodStart, flickrResp.Photos.Total

}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:28,代码来源:flickrImage.go

示例2: guessBadDate

func guessBadDate(f, i string, d time.Time) []Guess {
	var lines []string

	// Date might be missing an explicit year, so we fabricate one.
	curryear := time.Now().Year()
	fixup := func(t *time.Time) {
		if t.Year() == 0 {
			trace("Year 0 probably means the year was missing")
			*t = t.AddDate(curryear, 0, 0)
		}
	}
	fixup(&d)

	delta, ds := deltaNow(d)
	wantcal := false
	if delta > 2*24*time.Hour && delta < 365*24*time.Hour {
		wantcal = true
	}

	for _, loc := range TZs {
		t, err := time.ParseInLocation(f, i, loc)
		if err != nil {
			trace("previously parsable date is not parsable: %+v", d)
			continue
		}
		fixup(&t)
		zone, _ := t.Zone()
		l := fmt.Sprintf("From %s (%s): %s", zone, loc, t.Local())
		if !wantcal {
			_, s := deltaNow(t)
			l += fmt.Sprintf(" (%s)", s)
		}
		lines = append(lines, l)
	}
	ut, _ := time.ParseInLocation(f, i, time.UTC)
	fixup(&ut)
	lines = append(lines, fmt.Sprintf("As UNIX timestamp: %d", ut.Unix()))

	good := 0
	switch {
	case delta < 24*time.Hour:
		good = 200
	case delta < 7*24*time.Hour:
		good = 50
	case delta < 365*24*time.Hour:
		good = 10
	}
	additional := lines
	if wantcal || *alwaysCalendar {
		additional = sideBySide(additional, calendar(d))
	}

	return []Guess{{
		guess:      "In local time: " + d.String(),
		comment:    ds,
		additional: additional,
		goodness:   good,
		source:     "date string without timezone",
	}}
}
开发者ID:Feh,项目名称:guess,代码行数:60,代码来源:guess.go

示例3: Test_parseLastModified_BadValue

func Test_parseLastModified_BadValue(t *testing.T) {
	expected := time.Time{}
	test_string := `asdf`
	parsed, err := parseLastModified(test_string)
	assert.NotNil(t, err, fmt.Sprintf("unexpected nil error from parseLastModified on parsed item \"%s\"", test_string))
	assert.Equal(t, parsed.String(), expected.String(), fmt.Sprintf("parsed item \"%s\" did not match expected \"%s\"", parsed, expected))
}
开发者ID:ThatRubenAguilar,项目名称:go-sitemaps,代码行数:7,代码来源:sitemapparsing_test.go

示例4: RegisterService

//注册服务
func (s *ServiceAgent) RegisterService(serviceId, address string, port int, tags ...string) (err error) {
	if ok, _ := s.serviceExists(serviceId); ok {
		if err = s.UnregisterService(serviceId); err != nil {
			return
		}
	}

	agent := s.consulClient.Agent()
	reg := &consulApi.AgentServiceRegistration{
		ID:      serviceId,
		Name:    s.serviceName,
		Tags:    tags,
		Port:    port,
		Address: address,
		Check: &consulApi.AgentServiceCheck{
			TTL: fmt.Sprintf("%ds", TTL),
		},
	}
	err = agent.ServiceRegister(reg)
	if err != nil {
		return err
	}
	tk := time.NewTicker(time.Second * (TTL / 2))
	checkId := fmt.Sprintf("service:%s", serviceId)
	go func() {
		var now time.Time
		for range tk.C {
			now = time.Now()
			agent.PassTTL(checkId, now.String())
		}
		tk.Stop()
	}()

	return
}
开发者ID:zhsso,项目名称:consul,代码行数:36,代码来源:consul.go

示例5: dbFunc

func dbFunc(c *gin.Context) {
	if _, err := db.Exec("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); err != nil {
		c.String(http.StatusInternalServerError,
			fmt.Sprintf("Error creating database table: %q", err))
		return
	}

	if _, err := db.Exec("INSERT INTO ticks VALUES (now())"); err != nil {
		c.String(http.StatusInternalServerError,
			fmt.Sprintf("Error incrementing tick: %q", err))
		return
	}

	rows, err := db.Query("SELECT tick FROM ticks")
	if err != nil {
		c.String(http.StatusInternalServerError,
			fmt.Sprintf("Error reading ticks: %q", err))
		return
	}

	defer rows.Close()
	for rows.Next() {
		var tick time.Time
		if err := rows.Scan(&tick); err != nil {
			c.String(http.StatusInternalServerError,
				fmt.Sprintf("Error scanning ticks: %q", err))
			return
		}
		c.String(http.StatusOK, fmt.Sprintf("Read from DB: %s\n", tick.String()))
	}
}
开发者ID:jnrepo,项目名称:go-getting-started,代码行数:31,代码来源:main.go

示例6: schedule

func (s *scheduler) schedule(e event) (err error) {
	var on time.Time
	var duration time.Duration
	now := time.Now()
	zone, _ := now.Zone()
	if on, err = time.Parse("2006-01-02 "+time.Kitchen+" MST", now.Format("2006-01-02 ")+e.When+" "+zone); err != nil {
		log.Println("could not parse when of '" + e.When + "' for " + e.What)
		return
	}
	if duration, err = time.ParseDuration(e.Interval); err != nil {
		log.Println("could not parse interval of '" + e.Interval + "' for " + e.What)
		return
	}

	go func() {
		log.Println("scheduled '" + e.What + "' for: " + on.String())
		wait := time.Duration((on.UnixNano() - time.Now().UnixNano()) % int64(duration))
		if wait < 0 {
			wait += duration
		}
		time.Sleep(wait)
		s.maybeRun(time.Now(), e)
		for t := range time.NewTicker(duration).C {
			s.maybeRun(t, e)
		}
	}()
	return
}
开发者ID:dbrunton,项目名称:marvin,代码行数:28,代码来源:marvin.go

示例7: NewSessionCookie

// convencience method to create new encrypted cookie
// TODO: Resolve optionals
func NewSessionCookie(key []byte, name string, plaintext_value []byte, domain, path string, expires time.Time, maxage int, secure, httponly bool) (http.Cookie, error) {
	if name == "" || len(plaintext_value) == 0 || len(key) == 0 {
		return http.Cookie{}, errors.New("name, value and key are mandatory")
	}

	data, err := EncryptCookieValue(key, plaintext_value, ".")
	if err != nil {
		return http.Cookie{}, err
	}
	raw := name + "=" + data

	// Provide both Expires and Max-Age
	newcookie := http.Cookie{
		Name:       name,
		Value:      data,
		Path:       path,
		Expires:    expires,
		RawExpires: expires.String(),
		MaxAge:     maxage,
		Secure:     secure,
		HttpOnly:   httponly,
		Raw:        raw,
		Unparsed:   []string{raw},
	}

	return newcookie, nil
}
开发者ID:agdt3,项目名称:gosessioncookie,代码行数:29,代码来源:cookie.go

示例8: TestDateTimeLocal

func TestDateTimeLocal(t *testing.T) {
	zone := "Asia/Tokyo"
	tempFilename := TempFilename()
	db, err := sql.Open("sqlite3", tempFilename+"?_loc="+zone)
	if err != nil {
		t.Fatal("Failed to open database:", err)
	}
	db.Exec("CREATE TABLE foo (dt datetime);")
	db.Exec("INSERT INTO foo VALUES('2015-03-05 15:16:17');")

	row := db.QueryRow("select * from foo")
	var d time.Time
	err = row.Scan(&d)
	if err != nil {
		t.Fatal("Failed to scan datetime:", err)
	}
	if d.Hour() == 15 || !strings.Contains(d.String(), "JST") {
		t.Fatal("Result should have timezone", d)
	}
	db.Close()

	db, err = sql.Open("sqlite3", tempFilename)
	if err != nil {
		t.Fatal("Failed to open database:", err)
	}

	row = db.QueryRow("select * from foo")
	err = row.Scan(&d)
	if err != nil {
		t.Fatal("Failed to scan datetime:", err)
	}
	if d.UTC().Hour() != 15 || !strings.Contains(d.String(), "UTC") {
		t.Fatalf("Result should not have timezone %v %v", zone, d.String())
	}

	_, err = db.Exec("DELETE FROM foo")
	if err != nil {
		t.Fatal("Failed to delete table:", err)
	}
	dt, err := time.Parse("2006/1/2 15/4/5 -0700 MST", "2015/3/5 15/16/17 +0900 JST")
	if err != nil {
		t.Fatal("Failed to parse datetime:", err)
	}
	db.Exec("INSERT INTO foo VALUES(?);", dt)

	db.Close()
	db, err = sql.Open("sqlite3", tempFilename+"?_loc="+zone)
	if err != nil {
		t.Fatal("Failed to open database:", err)
	}

	row = db.QueryRow("select * from foo")
	err = row.Scan(&d)
	if err != nil {
		t.Fatal("Failed to scan datetime:", err)
	}
	if d.Hour() != 15 || !strings.Contains(d.String(), "JST") {
		t.Fatalf("Result should have timezone %v %v", zone, d.String())
	}
}
开发者ID:hujunlong,项目名称:go-sqlite3,代码行数:60,代码来源:sqlite3_test.go

示例9: get_bug

/*
Get a bug details.
*/
func get_bug(bug_id string) Bug {
	fmt.Println(bug_id)
	m := make(Bug)
	db, err := sql.Open("mysql", conn_str)
	defer db.Close()
	row := db.QueryRow("SELECT bug.summary, bug.status, bug.description, bug.version, bug.severity, bug.hardware, bug.priority, bug.whiteboard, bug.reported, bug.component_id, bug.subcomponent_id, bug.reporter, user.name, user.email from bugs as bug INNER JOIN users as user where bug.id=? and bug.reporter=user.id", bug_id)
	var summary, status, description, version, severity, hardware, priority, whiteboard, subcomponent_id, reporter_name, reporter_email []byte
	var reporter, component_id int
	var reported time.Time
	err = row.Scan(&summary, &status, &description, &version, &severity, &hardware, &priority, &whiteboard, &reported, &component_id, &subcomponent_id, &reporter, &reporter_name, &reporter_email)
	if err == nil {
		m["id"] = bug_id
		m["summary"] = string(summary)
		m["status"] = string(status)
		m["description"] = string(description)
		m["version"] = string(version)
		m["hardware"] = string(hardware)
		m["priority"] = string(priority)
		m["whiteboard"] = string(whiteboard)
		m["reported"] = reported.String()
		m["reporter"] = string(reporter)
		m["reporter_name"] = string(reporter_name)
		m["reporter_email"] = string(reporter_email)

	} else {
		fmt.Println(err)
	}
	return m
}
开发者ID:rtnpro,项目名称:bugspad,代码行数:32,代码来源:backend.go

示例10: RecentTracks

//RecentTracks returns a string of recently played tracks.
func (db *DB) RecentTracks() (s string, err error) {
	var (
		title  string
		artist string
		date   time.Time
	)

	rows, err := db.Table("tracks").
		Select("title, artist, date").
		Order("id desc").
		Limit(viper.GetInt("main.recent_tracks")).
		Rows()
	if err != nil {
		return "", err
	}
	defer rows.Close()

	var str []string
	for rows.Next() {
		rows.Scan(&title, &artist, &date)
		t, err := time.Parse("2006-01-02 15:04:05 -0700 UTC", date.String())
		if err != nil {
			return "", err
		}
		d := humanize.Time(t)
		str = append(str, fmt.Sprintf("%s - %s %s", artist, title, d))
	}
	return strings.Join(str, "\n"), nil
}
开发者ID:gregf,项目名称:localfm,代码行数:30,代码来源:database.go

示例11: hawkNonceNotFound

func (h *HawkHandler) hawkNonceNotFound(nonce string, t time.Time, creds *hawk.Credentials) bool {
	// From the Docs:
	//   The nonce is generated by the client, and is a string unique across all
	//   requests with the same timestamp and key identifier combination.
	var key string
	if creds != nil {
		key = nonce + t.String() + creds.ID
	} else {
		key = nonce + t.String()
	}

	// rotate the blooms?
	h.bloomLock.Lock()
	now := time.Now()
	if now.Sub(h.lastRotate) > h.bloomHalflife {
		h.bloomNow, h.bloomPrev = h.bloomPrev, h.bloomNow // switcheroo
		h.bloomNow.ClearAll()
		h.lastRotate = now
	}
	h.bloomLock.Unlock()

	if h.bloomNow.TestString(key) || h.bloomPrev.TestString(key) {
		return false
	}

	h.bloomNow.AddString(key)
	return true
}
开发者ID:mozilla-services,项目名称:go-syncstorage,代码行数:28,代码来源:hawkHandler.go

示例12: get_bug

/*
Get a bug details.
*/
func get_bug(bug_id string) Bug {
	fmt.Println(bug_id)
	m := make(Bug)
	db, err := sql.Open("mysql", conn_str)
	defer db.Close()
	row := db.QueryRow("SELECT status, description, version, severity, hardware, priority, whiteboard, reported, component_id, subcomponent_id, reporter from bugs where id=?", bug_id)
	var status, description, version, severity, hardware, priority, whiteboard, subcomponent_id []byte
	var reporter, component_id int
	var reported time.Time
	err = row.Scan(&status, &description, &version, &severity, &hardware, &priority, &whiteboard, &reported, &component_id, &subcomponent_id, &reporter)
	if err == nil {
		m["id"] = bug_id
		m["status"] = string(status)
		m["description"] = string(description)
		m["version"] = string(version)
		m["hardware"] = string(hardware)
		m["priority"] = string(priority)
		m["whiteboard"] = string(whiteboard)
		m["reported"] = reported.String()

	} else {
		fmt.Println(err)
	}
	return m
}
开发者ID:praveenkumar,项目名称:bugspad,代码行数:28,代码来源:backend.go

示例13: GenToken

func GenToken(t *time.Time) string {
	h := md5.New()
	buf := bytes.NewBufferString(t.String())
	h.Write(buf.Bytes())
	b := h.Sum(nil)
	return base64.RawURLEncoding.EncodeToString(b)
}
开发者ID:shaalx,项目名称:push,代码行数:7,代码来源:token.go

示例14: formatTime

func formatTime(t *time.Time) string {
	if t != nil {
		return t.String()
	} else {
		return ""
	}
}
开发者ID:brightbox,项目名称:gobrightbox-cli,代码行数:7,代码来源:output.go

示例15: TestTimestampWithTimeZone

func TestTimestampWithTimeZone(t *testing.T) {
	db := openTestConn(t)
	defer db.Close()

	tx, err := db.Begin()
	if err != nil {
		t.Fatal(err)
	}
	defer tx.Rollback()

	// try several different locations, all included in Go's zoneinfo.zip
	for _, locName := range []string{
		"UTC",
		"America/Chicago",
		"America/New_York",
		"Australia/Darwin",
		"Australia/Perth",
	} {
		loc, err := time.LoadLocation(locName)
		if err != nil {
			t.Logf("Could not load time zone %s - skipping", locName)
			continue
		}

		// Postgres timestamps have a resolution of 1 microsecond, so don't
		// use the full range of the Nanosecond argument
		refTime := time.Date(2012, 11, 6, 10, 23, 42, 123456000, loc)

		for _, pgTimeZone := range []string{"US/Eastern", "Australia/Darwin"} {
			// Switch Postgres's timezone to test different output timestamp formats
			_, err = tx.Exec(fmt.Sprintf("set time zone '%s'", pgTimeZone))
			if err != nil {
				t.Fatal(err)
			}

			var gotTime time.Time
			row := tx.QueryRow("select $1::timestamp with time zone", refTime)
			err = row.Scan(&gotTime)
			if err != nil {
				t.Fatal(err)
			}

			if !refTime.Equal(gotTime) {
				t.Errorf("timestamps not equal: %s != %s", refTime, gotTime)
			}

			// check that the time zone is set correctly based on TimeZone
			pgLoc, err := time.LoadLocation(pgTimeZone)
			if err != nil {
				t.Logf("Could not load time zone %s - skipping", pgLoc)
				continue
			}
			translated := refTime.In(pgLoc)
			if translated.String() != gotTime.String() {
				t.Errorf("timestamps not equal: %s != %s", translated, gotTime)
			}
		}
	}
}
开发者ID:Rompei,项目名称:bgm-server,代码行数:59,代码来源:encode_test.go


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