本文整理汇总了Golang中Time.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestSlot_list
func TestSlot_list(t *testing.T) {
_, client := mockServerClient(t)
layout := "2006-01-02"
prev, err := time.Parse(layout, "2015-12-14")
if err != nil {
t.Fatal(err)
}
to, _ := time.Parse(layout, "2015-12-15")
_ = prev
params := SlotParams{
From: prev,
To: to,
SelectedResources: []int{},
}
slots, err := client.ServiceSlot(427, params)
if err != nil {
t.Error(err)
}
if e := 4; len(slots) != e {
t.Fatalf("wrong number of slots returned got: %d wanted: %d",
len(slots), e)
}
}
示例2: getActivity
func (ctl *controller) getActivity(c web.C, w http.ResponseWriter, r *http.Request) {
teamID, _ := c.Env["team_id"].(string)
p := api.ActivityQueryParams{
AppID: r.URL.Query().Get("app"),
GroupID: r.URL.Query().Get("group"),
ChannelID: r.URL.Query().Get("channel"),
InstanceID: r.URL.Query().Get("instance"),
Version: r.URL.Query().Get("version"),
}
p.Severity, _ = strconv.Atoi(r.URL.Query().Get("severity"))
p.Start, _ = time.Parse(time.RFC3339, r.URL.Query().Get("start"))
p.End, _ = time.Parse(time.RFC3339, r.URL.Query().Get("end"))
p.Page, _ = strconv.ParseUint(r.URL.Query().Get("page"), 10, 64)
p.PerPage, _ = strconv.ParseUint(r.URL.Query().Get("perpage"), 10, 64)
activityEntriesJSON, err := ctl.api.GetActivityJSON(teamID, p)
switch err {
case nil:
w.Write(activityEntriesJSON)
case sql.ErrNoRows:
w.Write([]byte(`[]`))
default:
logger.Error("getActivity", "error", err, "teamID", teamID, "p", p)
http.Error(w, http.StatusText(400), 400)
}
}
示例3: parseDateTime
func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
switch len(str) {
case 10: // YYYY-MM-DD
if str == "0000-00-00" {
return
}
t, err = time.Parse(timeFormat[:10], str)
case 19: // YYYY-MM-DD HH:MM:SS
if str == "0000-00-00 00:00:00" {
return
}
t, err = time.Parse(timeFormat, str)
default:
err = fmt.Errorf("Invalid Time-String: %s", str)
return
}
// Adjust location
if err == nil && loc != time.UTC {
y, mo, d := t.Date()
h, mi, s := t.Clock()
t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
}
return
}
示例4: checkstatus
func checkstatus(p *os.Process, pname string, timest string) bool {
fmt.Println("checkstatus", pname, p)
reportlog[timest]["status"] = pname + " running"
reportlog[timest][pname+"start"] = time.Now().Format("20060102150405")
liner, _ := json.Marshal(reportlog)
ioutil.WriteFile("static/data/reportlog.json", liner, 0)
pw, _ := p.Wait()
fmt.Println("checkstatus over", p)
fmt.Println("timest=", timest)
reportlog[timest][pname+"stop"] = time.Now().Format("20060102150405")
t1, _ := time.Parse("20060102150405", reportlog[timest][pname+"stop"])
t2, _ := time.Parse("20060102150405", reportlog[timest][pname+"start"])
reportlog[timest][pname+"time"] = strconv.Itoa(int(t1.Sub(t2)) / 1e9)
fmt.Println("t1=", t1)
fmt.Println("t2=", t2)
fmt.Println("cost=", t1.Sub(t2))
status := pw.Success()
if status == true {
reportlog[timest]["status"] = pname + " success"
fmt.Println("checkstatus over success ", pname, p)
} else {
reportlog[timest]["status"] = pname + " failed"
fmt.Println("checkstatus over failed ", pname, p)
}
liner, _ = json.Marshal(reportlog)
ioutil.WriteFile("static/data/reportlog.json", liner, 0)
return status
}
示例5: TestLogsSinceFutureFollow
func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) {
// TODO Windows TP5 - Figure out why this test is so flakey. Disabled for now.
testRequires(c, DaemonIsLinux)
name := "testlogssincefuturefollow"
out, _ := dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`)
// Extract one timestamp from the log file to give us a starting point for
// our `--since` argument. Because the log producer runs in the background,
// we need to check repeatedly for some output to be produced.
var timestamp string
for i := 0; i != 100 && timestamp == ""; i++ {
if out, _ = dockerCmd(c, "logs", "-t", name); out == "" {
time.Sleep(time.Millisecond * 100) // Retry
} else {
timestamp = strings.Split(strings.Split(out, "\n")[0], " ")[0]
}
}
c.Assert(timestamp, checker.Not(checker.Equals), "")
t, err := time.Parse(time.RFC3339Nano, timestamp)
c.Assert(err, check.IsNil)
since := t.Unix() + 2
out, _ = dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name)
c.Assert(out, checker.Not(checker.HasLen), 0, check.Commentf("cannot read from empty log"))
lines := strings.Split(strings.TrimSpace(out), "\n")
for _, v := range lines {
ts, err := time.Parse(time.RFC3339Nano, strings.Split(v, " ")[0])
c.Assert(err, checker.IsNil, check.Commentf("cannot parse timestamp output from log: '%v'", v))
c.Assert(ts.Unix() >= since, checker.Equals, true, check.Commentf("earlier log found. since=%v logdate=%v", since, ts))
}
}
示例6: decodeTime
func decodeTime(r io.Reader, f reflect.Value) error {
s, err := decodeStr(r)
if err != nil {
return err
}
var t time.Time
if s != "" {
// Samsung has trailing dots.
s = strings.TrimRight(s, ".")
// Jolla Sailfish has trailing "Z".
s = strings.TrimRight(s, "Z")
t, err = time.Parse(timeFormat, s)
if err != nil {
// Nokia lumia has numTZ
t, err = time.Parse(timeFormatNumTZ, s)
if err != nil {
return err
}
}
}
f.Set(reflect.ValueOf(t))
return nil
}
示例7: NewAppointment
func NewAppointment(name string, day time.Weekday, start string, end string,
participants []int) (*Appointment, error) {
start_time, err := time.Parse(time.Kitchen, start)
if err != nil {
return nil, errors.New(start + " is not a valid start time. Format times like \"XX:YYPM\".")
}
end_time, err := time.Parse(time.Kitchen, end)
if err != nil {
return nil, errors.New(end + " is not a valid end time. Format times like \"XX:YYPM\".")
}
if !isValidTime(&start_time) || !isValidTime(&end_time) {
return nil, errors.New("Appointment times must start and end at XY:00 or XY:30.")
}
if end_time.Sub(start_time) <= 0 {
return nil, errors.New("Appointment must end after it starts.")
}
var parts [n]bool
for _, i := range participants {
if i < 1 || i > n {
return nil, fmt.Errorf("%d is not a valid user ID.", i)
}
parts[i-1] = true
}
a := Appointment{name, day, start_time, end_time, parts}
return &a, nil
}
示例8: SetBSON
func (t *TimePeriod) SetBSON(raw bson.Raw) error {
var str string
err := raw.Unmarshal(&str)
if err == nil {
str = strings.Replace(str, "\"", "", -1)
split := strings.Split(str, "/")
if len(split) == 2 {
t.FromTime, err = time.Parse(STD_TIME_FORMAT_PERIOD, split[0])
if err != nil {
return err
}
t.ToTime, err = time.Parse(STD_TIME_FORMAT_PERIOD, split[1])
if err != nil {
return err
}
} else {
t.FromTime, err = time.Parse(STD_TIME_FORMAT_INSTANT, split[0])
if err != nil {
return err
}
}
}
return err
}
示例9: rangeIntoDays
func rangeIntoDays(start, end string) ([]timeBlock, error) {
sT, err := time.Parse("20060102", start)
if err != nil {
return nil, err
}
eT, err := time.Parse("20060102", end)
if err != nil {
return nil, err
}
days := int(eT.Sub(sT).Hours())/24 + 1
dates := make([]timeBlock, days)
for i := 0; i < days; i++ {
durString := fmt.Sprintf("%dh", 24*i)
d, err := time.ParseDuration(durString)
if err != nil {
return nil, err
}
dayBegin := sT.Add(d)
dayEnd := dayBegin.Add(time.Duration(86399000000000))
dates[i] = timeBlock{dayBegin, dayEnd}
}
return dates, nil
}
示例10: parseTxtInvoice
func parseTxtInvoice(version, lino int, line string) (invoice *Invoice,
err error) {
invoice = &Invoice{}
var raised, due string
if version == fileVersion {
if _, err = fmt.Sscanf(line, "INVOICE ID=%d CUSTOMER=%d "+
"DEPARTMENT=%s RAISED=%s DUE=%s PAID=%t", &invoice.Id,
&invoice.CustomerId, &invoice.DepartmentId, &raised, &due,
&invoice.Paid); err != nil {
return nil, fmt.Errorf("invalid invoice %v line %d", err, lino)
}
} else {
if _, err = fmt.Sscanf(line, "INVOICE ID=%d CUSTOMER=%d "+
"RAISED=%s DUE=%s PAID=%t", &invoice.Id,
&invoice.CustomerId, &raised, &due, &invoice.Paid); err != nil {
return nil, fmt.Errorf("invalid invoice %v line %d", err, lino)
}
}
if invoice.Raised, err = time.Parse(dateFormat, raised); err != nil {
return nil, fmt.Errorf("invalid raised %v line %d", err, lino)
}
if invoice.Due, err = time.Parse(dateFormat, due); err != nil {
return nil, fmt.Errorf("invalid due %v line %d", err, lino)
}
if i := strings.Index(line, noteSep); i > -1 {
invoice.Note = strings.TrimSpace(line[i+len(noteSep):])
}
if version < fileVersion {
updateInvoice(invoice)
}
return invoice, nil
}
示例11: UnmarshalJSON
func (s *Summary) UnmarshalJSON(b []byte) error {
e := new(encodedSummary)
if err := json.Unmarshal(b, e); err != nil {
return err
}
s.Port = e.Port
s.Success = e.Success
s.Failure = e.Failure
s.Total = e.Total
var err error
if s.StartTime, err = time.Parse(time.RFC3339, e.StartTime); err != nil {
return err
}
if s.EndTime, err = time.Parse(time.RFC3339, e.EndTime); err != nil {
return err
}
s.Duration = s.EndTime.Sub(s.StartTime)
s.Senders = e.Senders
s.Timeout = time.Duration(e.Timeout) * time.Second
if e.TLSVersion != nil {
s.TLSVersion = *e.TLSVersion
}
if e.MailType != nil {
s.MailType = *e.MailType
}
if e.CAFile != nil {
s.CAFile = *e.CAFile
}
return nil
}
示例12: getFeeds
func getFeeds(feedSetting FeedSetting) {
resp, err := http.Get(feedSetting.URL)
//there's no reason to panic on this
if err != nil {
fmt.Printf("Couldn't reach URL: %v \n\n", feedSetting.URL)
return
}
var results Result
decoder := xml.NewDecoder(resp.Body)
decoder.CharsetReader = charset.NewReaderLabel
err = decoder.Decode(&results)
checkError(err)
//xml.Unmarshal([]byte(tempStr), &results)
session, _ := mgo.Dial("localhost")
feeds := session.DB("wcproc").C("feeds")
feed := Feed{}
feeds.Find(bson.M{"category": feedSetting.Name}).Sort("-date").One(&feed)
//convert the feed.date string to time.Time since unmarshal wont do it for me
for iter, element := range results.ItemList {
lastThree := element.PubDate[len(element.PubDate)-3:]
results.ItemList[iter].Link = strings.Trim(element.Link, " ")
if _, err := strconv.Atoi(lastThree); err == nil {
results.ItemList[iter].Date, err = time.Parse(time.RFC1123Z, element.PubDate)
checkError(err)
} else {
results.ItemList[iter].Date, err = time.Parse(time.RFC1123, element.PubDate)
checkError(err)
}
}
//check to see if any articles exist past the last article date in db
for iter, element := range results.ItemList {
if element.Date.After(feed.Date.Local()) {
//check title name against db for duplicates, some news feeds like to change the pubdate over the length of 6 hours
matchup := Feed{}
feeds.Find(bson.M{"title": element.Title, "category": feedSetting.Name}).One(&matchup)
if matchup.Category == "" {
fmt.Printf("adding: %v -- %v \n", element.Date, element.Title)
results.ItemList[iter].ArticleId = feedSetting.ArticleId
results.ItemList[iter].Category = feedSetting.Name
_ = feeds.Insert(results.ItemList[iter])
}
}
}
session.Close()
}
示例13: machineFromMongodb
func machineFromMongodb(db *mongodb.MongoDB) (*machines, error) {
from, err := time.Parse(time.RFC3339, "2015-03-07T13:15:00Z")
if err != nil {
return nil, err
}
to, err := time.Parse(time.RFC3339, "2015-04-10T07:30:00Z")
if err != nil {
return nil, err
}
machines := newMachines()
err = db.Run("jMachines", func(c *mgo.Collection) error {
var m koding.Machine
iter := c.Find(
bson.M{
"createdAt": bson.M{
"$gte": from.UTC(),
"$lt": to.UTC(),
},
// "status.state": machinestate.Stopped.String(),
},
).Iter()
for iter.Next(&m) {
machines.docs = append(machines.docs, m)
}
return iter.Close()
})
return machines, err
}
示例14: TestListHealingHistoryCmdRun
func (s *S) TestListHealingHistoryCmdRun(c *check.C) {
var buf bytes.Buffer
context := cmd.Context{Stdout: &buf}
trans := &cmdtest.ConditionalTransport{
Transport: cmdtest.Transport{Message: healingJsonData, Status: http.StatusOK},
CondFunc: func(req *http.Request) bool {
return req.URL.Path == "/docker/healing"
},
}
manager := cmd.Manager{}
client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
healing := &ListHealingHistoryCmd{}
err := healing.Run(&context, client)
c.Assert(err, check.IsNil)
startT, _ := time.Parse(time.RFC3339, "2014-10-23T08:00:00.000Z")
endT, _ := time.Parse(time.RFC3339, "2014-10-23T08:30:00.000Z")
startTStr := startT.Local().Format(time.Stamp)
endTStr := endT.Local().Format(time.Stamp)
expected := fmt.Sprintf(`Node:
+-----------------+-----------------+---------+---------+---------+-------+
| Start | Finish | Success | Failing | Created | Error |
+-----------------+-----------------+---------+---------+---------+-------+
| %s | %s | true | addr1 | addr2 | |
+-----------------+-----------------+---------+---------+---------+-------+
Container:
+-----------------+-----------------+---------+------------+------------+-------+
| Start | Finish | Success | Failing | Created | Error |
+-----------------+-----------------+---------+------------+------------+-------+
| %s | %s | false | 1234567890 | | err1 |
+-----------------+-----------------+---------+------------+------------+-------+
| %s | %s | true | 1234567890 | 9234567890 | |
+-----------------+-----------------+---------+------------+------------+-------+
`, startTStr, endTStr, startTStr, endTStr, startTStr, endTStr)
c.Assert(buf.String(), check.Equals, expected)
}
示例15: Extract
// Extract will retrieve a Config resource from an operation result.
func (r commonResult) Extract() (*Config, error) {
if r.Err != nil {
return nil, r.Err
}
var response struct {
Config Config `mapstructure:"configuration"`
}
err := mapstructure.Decode(r.Body, &response)
val := r.Body.(map[string]interface{})["configuration"].(map[string]interface{})
if t, ok := val["created"].(string); ok && t != "" {
creationTime, err := time.Parse(time.RFC3339, t)
if err != nil {
return &response.Config, err
}
response.Config.Created = creationTime
}
if t, ok := val["updated"].(string); ok && t != "" {
updatedTime, err := time.Parse(time.RFC3339, t)
if err != nil {
return &response.Config, err
}
response.Config.Updated = updatedTime
}
return &response.Config, err
}