// 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 }
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", }} }
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)) }
//注册服务 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 }
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())) } }
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 }
// 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 }
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()) } }
/* 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 }
//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 }
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 }
/* 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 }
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) }
func formatTime(t *time.Time) string { if t != nil { return t.String() } else { return "" } }
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) } } } }
func InsertStart(t time.Time, id string, cs string) uint { flight := initializeFlight(id, cs) flight.Start = t.Unix() flight.FormattedStart = t.String() db.Save(&flight) return flight.Id }
// serve starts the DNS server and blocks. func serve(opt *Options) { dockerTLS, err := tlsConfig(opt.tlsDir, opt.tlsVerify) if err != nil { log.Fatalf("Error establishing TLS config: %v", err) } rrs := rrstore.New() cluster, err := swarm.New(opt.swarmAddr, dockerTLS) if err != nil { log.Fatalf("Error initializing Swarm: %v", err) } dns := clusterdns.New(opt.domain, rrs, cluster) cancel := make(chan struct{}) defer close(cancel) errCh, okCh := dns.StartRefreshing(opt.refreshInterval, opt.refreshTimeout, cancel) go func() { var lastSuccess time.Time var start = time.Now() var errs = 0 var ok = 0 for { // Exit if records are stale. Here we prefer consistency over // liveliness/availability. if (ok > 0 && time.Since(lastSuccess) > opt.stalenessPeriod) || (ok == 0 && time.Since(start) > opt.stalenessPeriod) { close(cancel) var last string if lastSuccess.IsZero() { last = "never" } else { last = lastSuccess.String() } log.Fatalf("Fatal: exiting rather than serving stale records. Staleness period: %v, last success: %s", opt.stalenessPeriod, last) } select { case err := <-errCh: errs++ log.Printf("Refresh error (#%d): %v ", errs, err) case <-okCh: errs = 0 // reset errs ok++ lastSuccess = time.Now() log.Printf("Successfully refreshed records.") case <-cancel: log.Fatal("Fatal: Refreshing records cancelled.") } } }() srv := server.New(opt.domain, opt.bindAddr, rrs, opt.recurse, opt.nameservers) log.Fatal(srv.ListenAndServe()) }
// LastConnection turns the *time.Time returned from the API server // into a user facing string with either exact time or a user friendly // string based on the args. func LastConnection(connectionTime *time.Time, now time.Time, exact bool) string { if connectionTime == nil { return "never connected" } if exact { return connectionTime.String() } return UserFriendlyDuration(*connectionTime, now) }
// SetDeadline sets the read and write deadlines associated // with the connection func (conn *RawConn) SetDeadline(t time.Time) error { if tracing { defer trace.End(trace.Begin(t.String())) } // https://golang.org/src/net/fd_poll_runtime.go#L133 // consider implementing this by making RawConn a netFD // if we can find a way around the lack of export return nil }
func (m *mockViewsTable) Insert(adID string, refererURL string, originIP string, contentGeneratedOn time.Time, sessionID string) (sql.Result, error) { m.data["adID"] = adID m.data["refererURL"] = refererURL m.data["originIP"] = originIP m.data["contentGeneratedOn"] = contentGeneratedOn.String() m.data["sessionID"] = sessionID return &datatest.MockDBResult{1, 1}, nil }
// Compile all information exported through the hackerspace API and send it // back to the requestor. func (a *SpaceAPI) ServeHTTP(rw http.ResponseWriter, req *http.Request) { var msg = proto.Clone(a.conf.SpaceapiMd) var md *doorky.SpaceAPIMetadata var door *doorky.DoorSecret var out []byte var err error var ok bool md, ok = msg.(*doorky.SpaceAPIMetadata) if !ok { log.Print("Error: message is not of type SpaceAPIMetadata") http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } for _, door = range a.conf.Secret { var lockInfo = new(doorky.SpaceAPIDoorLockSensor) var name = door.GetName() var ts time.Time var isOpen bool ts, isOpen, err = a.ts.LastValue(name) if err != nil { log.Print("Error fetching door status for ", name, ": ", err) continue } lockInfo.Value = proto.Bool(!isOpen) lockInfo.Location = proto.String(door.GetLocation()) lockInfo.Name = proto.String(name) lockInfo.Description = proto.String("Last update: " + ts.String()) if md.Sensors == nil { md.Sensors = new(doorky.SpaceAPISensors) } md.Sensors.DoorLocked = append(md.Sensors.DoorLocked, lockInfo) if a.conf.PrimaryDoor != nil && a.conf.GetPrimaryDoor() == name { md.State.Open = proto.Bool(isOpen) md.State.Lastchange = proto.Int64(ts.Unix()) } } out, err = json.MarshalIndent(md, " ", " ") if err != nil { log.Print("Error marshalling JSON: ", err) http.Error(rw, http.StatusText(http.StatusInternalServerError)+": "+ "Error marshalling response: "+err.Error(), http.StatusInternalServerError) } _, err = rw.Write(out) if err != nil { log.Print("Error writing response: ", err) } }
func (*OrientDBBackend) getTimeClause(t *time.Time) string { var t2 time.Time if t == nil { t2 = time.Now() } else { t2 = *t } s := t2.String() return fmt.Sprintf("CreatedAt <= '%s' AND (DeletedAt > '%s' OR DeletedAt is NULL)", s, s) }
func (m *mockACTable) Insert(adID string, refererURL string, destinationURL string, originIP string, linkGeneratedOn time.Time, linkTag string, sessionID string) (sql.Result, error) { m.data["adID"] = adID m.data["refererURL"] = refererURL m.data["destinationURL"] = destinationURL m.data["originIP"] = originIP m.data["linkGeneratedOn"] = linkGeneratedOn.String() m.data["linkTag"] = linkTag m.data["sessionID"] = sessionID return &datatest.MockDBResult{1, 1}, nil }
func GetProductById(prod_id int64) (ProductInput, error) { var prd ProductInput buff := bytes.NewBufferString(` SELECT product_id, product_name, shop_id, child_cat_id, short_desc, min_order, price_currency, normal_price, status, position, must_insurance, condition, weight_unit, weight, last_update_price FROM ws_product WHERE product_id = $1 LIMIT 1 `) query := db.Rebind(buff.String()) row := db.QueryRow(query, prod_id) var normal_price string var lastprc time.Time err := row.Scan( &prd.ProductId, &prd.ProductName, &prd.ShopId, &prd.ChildCatId, &prd.ShortDesc, &prd.MinOrder, &prd.PriceCurrency, &normal_price, &prd.Status, &prd.Position, &prd.Insurance, &prd.Condition, &prd.Weight.Unit, &prd.Weight.Numeric, &lastprc) prd.LastPrcUpdate = lastprc.String() prd.NormalPrice, _ = strconv.ParseInt(normal_price, 10, 64) if err != nil { return ProductInput{}, err } else { return prd, nil } }
func Test_Conn_Scan_Time(t *testing.T) { tests := []*timeTest{ newTimeTest( "SELECT DATE '%s';", dateFormat, "2010-08-14"), newTimeTest( "SELECT TIME '%s';", timeFormat, "18:43:32"), newTimeTest( "SELECT TIME WITH TIME ZONE '%s';", timeFormat+"-07", "18:43:32+02"), newTimeTest( "SELECT TIMESTAMP '%s';", timestampFormat, "2010-08-14 18:43:32"), newTimeTest( "SELECT TIMESTAMP WITH TIME ZONE '%s';", timestampFormat+"-07", "2010-08-14 18:43:32+02"), } for _, test := range tests { withConn(t, func(conn *Conn) { _, err := conn.Execute("SET TimeZone = 02; SET DateStyle = ISO") if err != nil { t.Error("failed to set time zone or date style:", err) return } var seconds int64 _, err = conn.Scan(test.command, &seconds) if err != nil { t.Error(err) return } if seconds != test.seconds { t.Errorf("'%s' failed - have: '%d', but want '%d'", test.command, seconds, test.seconds) } var tm time.Time _, err = conn.Scan(test.command, &tm) if err != nil { t.Error(err) return } timeString := tm.String() if timeString != test.timeString { t.Errorf("'%s' failed - have: '%s', but want '%s'", test.command, timeString, test.timeString) } }) } }
// returns a simple state of health page. If heartbeat times in the // DB are old then it also returns an http status of 500. // Not useful for inclusion in app metrics so weft not used. func sohEsb(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", HtmlContent) if res := weft.CheckQuery(r, []string{}, []string{}); !res.Ok { w.Header().Set("Surrogate-Control", "max-age=86400") w.WriteHeader(http.StatusBadRequest) return } var b bytes.Buffer b.Write([]byte(head)) b.Write([]byte(`<p>Current time is: ` + time.Now().UTC().String() + `</p>`)) b.Write([]byte(`<h3>Messaging</h3>`)) var bad bool var s string var t time.Time b.Write([]byte(`<table><tr><th>Service</th><th>Time Received</th></tr>`)) rows, err := db.Query("select serverid, timereceived from haz.soh") if err == nil { defer rows.Close() for rows.Next() { err := rows.Scan(&s, &t) if err == nil { if t.Before(time.Now().UTC().Add(old)) { bad = true b.Write([]byte(`<tr class="tr error">`)) } else { b.Write([]byte(`<tr>`)) } b.Write([]byte(`<td>` + s + `</td><td>` + t.String() + `</td></tr>`)) } else { bad = true b.Write([]byte(`<tr class="tr error"><td>DB error</td><td>` + err.Error() + `</td></tr>`)) } } rows.Close() } else { log.Printf("ERROR: %v", err) bad = true b.Write([]byte(`<tr class="tr error"><td>DB error</td><td>` + err.Error() + `</td></tr>`)) } b.Write([]byte(`</table>`)) b.Write([]byte(foot)) if bad { w.WriteHeader(http.StatusServiceUnavailable) } b.WriteTo(w) }
func GenLogEx(msg string, begin, end time.Time, duration time.Duration) string { durationf := duration.Seconds() sBegin := begin.String() msIdx := 23 sBegin = (string)([]byte(sBegin)[10:msIdx]) sEnd := end.String() sEnd = (string)([]byte(sEnd)[10:msIdx]) return fmt.Sprintf("%-45s %-15s %-15s %15.3fs", msg, sBegin, sEnd, durationf) }
// TODO: Create a function just like this that returns a list of HourEvent structs func (plans *Plans) PrintHourEvents(date time.Time) { fmt.Printf("What's up at %s?\n", date.String()) s := "" for _, pp := range plans.all { s += pp.ViewHour(date) } if s == "" { fmt.Println("Nothing!") } else { fmt.Println(s) } }
func (ce *ChatEngine) GetLastSeen(username string) string { encodedTime, err := ce.chatState.userInfo.Get(username, "lastseen") if err == nil { var then time.Time err = then.GobDecode([]byte(encodedTime)) if err == nil { timestamp := then.String() return timestamp[11:19] } } return "never" }
// Format the time.Time instance so that forecast.io API can read it // return something like: "2013-09-15T16:37:00" func formattedTime(t time.Time) string { // t.String() will look something like c 21:59:55.459808262 -0700 PDT // Split time string on spaces (splits between: date/time, time/zone_diff, zone_diff/zone) timeParts := strings.Split(t.String(), " ") // Get date in format 2009-11-10 stringDate := timeParts[0] // Get time without part-seconds (21:59:55) stringTime := strings.Split(timeParts[1], ".")[0] // Final output will look like 2009-11-10T21:59:55 return (stringDate + "T" + stringTime) }