func loadZone(zone string) *time.Location { loc, err := time.LoadLocation(zone) if err == nil { return loc } // Pure ASCII, but OK. Allow us to say "paris" as well as "Paris". if len(zone) > 0 && 'a' <= zone[0] && zone[0] <= 'z' { zone = string(zone[0]+'A'-'a') + string(zone[1:]) } // See if there's a file with that name in /usr/share/zoneinfo files, _ := filepath.Glob("/usr/share/zoneinfo/*/" + zone) if len(files) >= 1 { if len(files) > 1 { fmt.Fprintf(os.Stderr, "now: multiple time zones; using first of %v\n", files) } loc, err = time.LoadLocation(files[0][len("/usr/share/zoneinfo/"):]) if err == nil { return loc } } fmt.Fprintf(os.Stderr, "now: %s\n", err) os.Exit(1) return nil }
func TestTime(t *testing.T) { cet, err := time.LoadLocation("CET") require.NoError(t, err) ast, err := time.LoadLocation("Australia/Sydney") require.NoError(t, err) firstJanuary2015CET := time.Date(2015, 1, 1, 0, 0, 0, 0, cet) require.Equal(t, int64(1420066800), firstJanuary2015CET.Unix()) require.Equal(t, int64(1420066800+3600), LocalUnix(firstJanuary2015CET)) require.Equal(t, 3600, TimezoneOffsetNoDST(firstJanuary2015CET)) require.Equal(t, 0, DaylightSavingsOffset(firstJanuary2015CET)) fall2015CET := time.Date(2015, 9, 23, 0, 0, 0, 0, cet) require.Equal(t, int64(1442959200), fall2015CET.Unix()) require.Equal(t, int64(1442959200+3600+3600), LocalUnix(fall2015CET)) require.Equal(t, 3600, TimezoneOffsetNoDST(fall2015CET)) require.Equal(t, 3600, DaylightSavingsOffset(fall2015CET)) firstJan2015AST := time.Date(2015, 1, 1, 0, 0, 0, 0, ast) require.Equal(t, int64(1420030800), firstJan2015AST.Unix()) require.Equal(t, int64(1420030800+36000+3600), LocalUnix(firstJan2015AST)) require.Equal(t, 36000, TimezoneOffsetNoDST(firstJan2015AST)) require.Equal(t, 3600, DaylightSavingsOffset(firstJan2015AST)) fall2015AST := time.Date(2015, 9, 23, 0, 0, 0, 0, ast) require.Equal(t, int64(1442930400), fall2015AST.Unix()) require.Equal(t, int64(1442930400+36000), LocalUnix(fall2015AST)) require.Equal(t, 36000, TimezoneOffsetNoDST(fall2015AST)) require.Equal(t, 0, DaylightSavingsOffset(fall2015AST)) }
//设置时区,参数错误则使用Asia/Shanghai func (l *Logger) SetTimeLocation(name string) { var err error if l.timeLocation, err = time.LoadLocation(name); nil != err { l.timeLocation, _ = time.LoadLocation("Asia/Shanghai") l.Warningf("time_location_error %s, use Asia/Shanghai instead", err.Error()) } }
func PostComments(w http.ResponseWriter, r *http.Request) { tmpl := plate.NewTemplate(w) id, _ := strconv.Atoi(r.URL.Query().Get(":id")) post, _ := models.Post{ID: id}.Get() tmpl.FuncMap["formatDateForURL"] = func(dt time.Time) string { tlayout := "1-02-2006" Local, _ := time.LoadLocation("US/Central") return dt.In(Local).Format(tlayout) } tmpl.FuncMap["formatDate"] = func(dt time.Time) string { tlayout := "01/02/2006 3:04 PM" Local, _ := time.LoadLocation("US/Central") return dt.In(Local).Format(tlayout) } tmpl.Bag["PageTitle"] = "Post Comments" tmpl.Bag["post"] = post tmpl.ParseFile("templates/blog/navigation.html", false) tmpl.ParseFile("templates/blog/postcomments.html", false) err := tmpl.Display(w) if err != nil { log.Println(err) } }
func Index(w http.ResponseWriter, r *http.Request) { tmpl := plate.NewTemplate(w) posts, _ := models.Post{}.GetAll() tmpl.FuncMap["formatDateForURL"] = func(dt time.Time) string { tlayout := "1-02-2006" Local, _ := time.LoadLocation("US/Central") return dt.In(Local).Format(tlayout) } tmpl.FuncMap["formatDate"] = func(dt time.Time) string { tlayout := "01/02/2006 3:04 PM" Local, _ := time.LoadLocation("US/Central") return dt.In(Local).Format(tlayout) } tmpl.FuncMap["showCommentsLink"] = func(c models.Comments) bool { return len(c.Approved) > 0 && len(c.Unapproved) > 0 } tmpl.Bag["PageTitle"] = "Blog Posts" tmpl.Bag["posts"] = posts tmpl.ParseFile("templates/blog/navigation.html", false) tmpl.ParseFile("templates/blog/index.html", false) err := tmpl.Display(w) if err != nil { log.Println(err) } }
func init() { DefaultTimeLoc, _ = time.LoadLocation("Local") HtmlFuncBoot.Register(func(w *Web) { // Convert to Default Timezone. w.HtmlFunc["time"] = func(clock time.Time) time.Time { return clock.In(w.TimeLoc) } // Convert to Timezone w.HtmlFunc["timeZone"] = func(zone string, clock time.Time) time.Time { loc, err := time.LoadLocation(zone) w.Check(err) return clock.In(loc) } // Format time, leave empty for default w.HtmlFunc["timeFormat"] = func(format string, clock time.Time) string { if format == "" { format = w.TimeFormat } return clock.Format(format) } }) }
func TestEqual(t *testing.T) { loc, _ := time.LoadLocation("America/Chicago") start := time.Date(2015, time.October, 10, 0, 0, 0, 0, loc) end := time.Date(2015, time.October, 12, 0, 0, 0, 0, loc) chicShift, err := NewShift(start, end) if err != nil { t.Fatalf("Problem creating new shift: %v", err) } loc, err = time.LoadLocation("America/New_York") start = time.Date(2015, time.October, 10, 1, 0, 0, 0, loc) end = time.Date(2015, time.October, 12, 1, 0, 0, 0, loc) nycShift, err := NewShift(start, end) if err != nil { t.Fatalf("Problem creating new shift: %v", err) } if !chicShift.Equal(nycShift) { t.Fatalf("Shifts should be equal even with different timezones") } start = time.Date(2015, time.October, 10, 2, 0, 0, 0, loc) end = time.Date(2015, time.October, 12, 2, 0, 0, 0, loc) nycShift, err = NewShift(start, end) if err != nil { t.Fatalf("Problem creating new shift: %v", err) } if chicShift.Equal(nycShift) { t.Fatalf("Shifts should not equal because they represent different times") } }
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 init() { var err error WestCoastUSLocation, err = time.LoadLocation("America/Los_Angeles") panicOn(err) EastCoastUSLocation, err = time.LoadLocation("America/New_York") panicOn(err) LondonLocation, err = time.LoadLocation("Europe/London") panicOn(err) }
func getDateForRegion(credentials *auth.Credentials, isManta bool) string { if isManta { location, _ := time.LoadLocation(jpc.Locations["us-east-1"]) return time.Now().In(location).Format(time.RFC1123) } else { location, _ := time.LoadLocation(jpc.Locations[credentials.Region()]) return time.Now().In(location).Format(time.RFC1123) } }
func (f Field) TimeZone() *time.Location { if val, has := f.Params["TZID"]; has && len(val) == 1 { loc, err := time.LoadLocation(val[0]) if err == nil { return loc } } loc, _ := time.LoadLocation("UTC") return loc }
func (p *WeatherPane) GetWeather() { enableWeatherPane = false for { site := &model.Site{} err := p.siteModel.Call("fetch", config.MustString("siteId"), site, time.Second*5) if err == nil && (site.Longitude != nil || site.Latitude != nil) { p.site = site globalSite = site if site.TimeZoneID != nil { if timezone, err = time.LoadLocation(*site.TimeZoneID); err != nil { log.Warningf("error while setting timezone (%s): %s", *site.TimeZoneID, err) timezone, _ = time.LoadLocation("Local") } } break } log.Infof("Failed to get site, or site has no location.") time.Sleep(time.Second * 2) } for { p.weather.DailyByCoordinates( &owm.Coordinates{ Longitude: *p.site.Longitude, Latitude: *p.site.Latitude, }, 1, ) if len(p.weather.List) > 0 { filename := util.ResolveImagePath("weather/" + p.weather.List[0].Weather[0].Icon + ".png") if _, err := os.Stat(filename); os.IsNotExist(err) { enableWeatherPane = false fmt.Printf("Couldn't load image for weather: %s", filename) bugsnag.Notify(fmt.Errorf("Unknown weather icon: %s", filename), p.weather) } else { p.image = util.LoadImage(filename) enableWeatherPane = true } } time.Sleep(weatherUpdateInterval) } }
func (s *TimeUtilSuite) TestTimezone(c *C) { ny, _ := time.LoadLocation("America/New_York") msk, _ := time.LoadLocation("Europe/Moscow") t := time.Unix(1447848900, 0) c.Assert(getTimezone(t.UTC().In(ny), false), Equals, "-0500") c.Assert(getTimezone(t.UTC().In(ny), true), Equals, "-05:00") c.Assert(getTimezone(t.UTC().In(msk), false), Equals, "+0300") c.Assert(getTimezone(t.UTC().In(msk), true), Equals, "+03:00") }
func main() { tz := "US/Pacific" if cattz, ok := os.LookupEnv("CATZ"); ok { tz = cattz } else { stdtz, ok := os.LookupEnv("TZ") if ok { tz = stdtz } } srcTZ := flag.String("srctz", "UTC", "input time zone") destTZ := flag.String("outtz", tz, "output time zone (defaults to $CATZ or $TZ env if available)") debug := flag.Bool("d", false, "enable debug logging") timeFormat := flag.String("t", "%Y-%m-%d %H", "strftime format") first := flag.Bool("first", false, "only replace first timestamp match per line") flag.Parse() sourceLocation, err := time.LoadLocation(*srcTZ) if err != nil { fmt.Fprintf(os.Stderr, "ERROR input TZ %s not known\n", *srcTZ) os.Exit(1) } destLocation, err := time.LoadLocation(*destTZ) if err != nil { fmt.Fprintf(os.Stderr, "ERROR output TZ %s not known\n", *destTZ) os.Exit(1) } c := &controller{ srcLoc: sourceLocation, destLoc: destLocation, buf: &bytes.Buffer{}, debug: *debug, } // verify we know how to handle the time format c.format, err = strftime.New(*timeFormat) if err != nil { fmt.Fprintf(os.Stderr, "ERROR time format [%s] had problem converting to go format%s\n", *timeFormat, err) os.Exit(1) } err = c.strftimeToRE(*timeFormat) if err != nil { fmt.Fprintf(os.Stderr, "ERROR time format [%s] had problem to regex %s\n", *timeFormat, err) os.Exit(1) } // only replace first timestamp occurance, or replace all if *first { c.matchLimit = 1 } else { c.matchLimit = -1 } os.Exit(c.execute()) }
func init() { var err error CONST = new(c) CONST.DBNAME = "data.sqlite" CONST.UPLOADPATH = "files" CONST.PERPAGE = 10//todo read from config CONST.TIMEZONE, err = time.LoadLocation(beego.AppConfig.String("TimeZone")) if err != nil { CONST.TIMEZONE, _ = time.LoadLocation("Asia/Shanghai") } }
func (e *Results) parseDateTime() time.Time { // set the timezone, otherwise UTC will be used loc, err := time.LoadLocation("America/New_York") if err != nil { // couldn't set timezone, falling back to UTC loc, _ = time.LoadLocation("UTC") } // parse the unix timestamp, and apply our timezone t := time.Unix(0, e.Time*int64(time.Millisecond)).In(loc) return t }
func date() (string, error) { localTZ, err := time.LoadLocation("Europe/Vilnius") if err != nil { return "", err } extraTZ, err := time.LoadLocation("Europe/London") if err != nil { return "", err } local := time.Now().In(localTZ).Format("Mon _2 Jan 15:04") extra := "UK " + time.Now().In(extraTZ).Format("15:04") return fmt.Sprintf("^fg(white)%s ^i(%s) ^fg()%s", local, xbm("clock2"), extra), nil }
// Takes year/month/day (in a variety of formats) and HH:MM parameters // Checks if the time is valid and returns error if it is not // Parses in the location of Santiago func ReturnTime(d string, t string) (time.Time, error) { loc, err := time.LoadLocation("America/Santiago") if err != nil { return time.Time{}, NewError(err, "Error de servidor", 500) } layout := returnTimeLayout(d) splits := strings.Split(t, ":") if len(splits) == 1 { if utf8.RuneCountInString(t) == 2 { layout += " 15" } else if utf8.RuneCountInString(t) == 1 { t = "0" + t layout += " 15" } else if utf8.RuneCountInString(t) == 4 { layout += " 1504" } } else if len(splits) == 2 { layout += " 15:04" } timeVar, err := time.ParseInLocation(layout, d+" "+t, loc) if err != nil { return time.Time{}, NewError(nil, "Formato de tiempo invalido", 400) } return timeVar, nil }
func init() { var err error localLoc, err = time.LoadLocation("Europe/Berlin") if nil != err { panic(err) } }
// Create new media playlist // Add three segments to media playlist // Set program date and time for 2nd segment. // Set discontinuity tag for the 2nd segment. func TestProgramDateTimeForMediaPlaylist(t *testing.T) { var e error p, e := NewMediaPlaylist(3, 4) if e != nil { t.Fatalf("Create media playlist failed: %s", e) } p.Close() if e = p.Append("test01.ts", 5.0, ""); e != nil { t.Errorf("Add 1st segment to a media playlist failed: %s", e) } if e = p.Append("test02.ts", 6.0, ""); e != nil { t.Errorf("Add 2nd segment to a media playlist failed: %s", e) } loc, _ := time.LoadLocation("Europe/Moscow") if e = p.SetProgramDateTime(time.Date(2010, time.November, 30, 16, 25, 0, 125*1e6, loc)); e != nil { t.Error("Can't set program date and time") } if e = p.SetDiscontinuity(); e != nil { t.Error("Can't set discontinuity tag") } if e = p.Append("test03.ts", 6.0, ""); e != nil { t.Errorf("Add 3nd segment to a media playlist failed: %s", e) } //fmt.Println(p.Encode().String()) }
func builtinTimeIn(arg []interface{}, ctx map[interface{}]interface{}) (v interface{}, err error) { switch x := arg[0].(type) { case nil: return nil, nil case time.Time: switch y := arg[1].(type) { case nil: return nil, nil case string: loc := time.Local switch y { case "local": default: loc, err = time.LoadLocation(y) if err != nil { return } } return x.In(loc), nil default: return nil, invArg(x, "timeIn") } default: return nil, invArg(x, "timeIn") } }
func builtinParseTime(arg []interface{}, ctx map[interface{}]interface{}) (v interface{}, err error) { var a [2]string for i, v := range arg { switch x := v.(type) { case nil: return nil, nil case string: a[i] = x default: return nil, invArg(x, "parseTime") } } t, err := time.Parse(a[0], a[1]) if err != nil { return nil, err } ls := t.Location().String() if ls == "UTC" { return t, nil } l, err := time.LoadLocation(ls) if err != nil { return t, nil } return time.ParseInLocation(a[0], a[1], l) }
func TestCParse(t *testing.T) { loc, _ := time.LoadLocation("America/New_York") a, _ := CParseInLocation("%Y-%m-%d", "1980-06-19", loc) if a.Format("2006-01-02") != "1980-06-19" { t.Error("CParseInLocation") } }
func View(w http.ResponseWriter, r *http.Request) { tmpl := plate.NewTemplate(w) params := r.URL.Query() id, _ := strconv.Atoi(params.Get(":id")) contact := models.Contact{ID: id} err := contact.Get() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl.FuncMap["formatDate"] = func(dt time.Time) string { tlayout := "Mon, 01/02/06, 3:04PM MST" Local, _ := time.LoadLocation("US/Central") return dt.In(Local).Format(tlayout) } tmpl.Bag["PageTitle"] = "View Contact Details" tmpl.Bag["contact"] = contact tmpl.ParseFile("templates/website/navigation.html", false) tmpl.ParseFile("templates/contact/view.html", false) err = tmpl.Display(w) if err != nil { log.Println(err) } }
func getTweetFromAPI(sinceID string) (tweets []Tweet, err error) { api := anaconda.NewTwitterApi(os.Getenv("ACCESS_TOKEN"), os.Getenv("ACCESS_TOKEN_SECRET")) v := url.Values{} v.Add("screen_name", "habomaijiro") v.Add("count", "200") if sinceID != "" { v.Add("since_id", sinceID) } tl, err := api.GetUserTimeline(v) if err != nil { return } jst, err := time.LoadLocation("Asia/Tokyo") if err != nil { return } tweets = make([]Tweet, len(tl)) for i, v := range tl { var t Tweet t.ID = v.IdStr if parsedT, err := time.Parse(time.RubyDate, v.CreatedAt); err == nil { t.Date = parsedT.In(jst) } t.ImageURLs = make([]string, len(v.Entities.Media)) for j, m := range v.Entities.Media { t.ImageURLs[j] = m.Media_url_https } analizeText(&t, v.Text) tweets[i] = t } return }
func TestFastMarshalJSON(t *testing.T) { aTime := time.Date(2015, 5, 29, 11, 1, 2, 3, time.UTC) json, err := FastMarshalJSON(aTime) if err != nil { t.Fatal(err) } expected := "\"2015-05-29T11:01:02.000000003Z\"" if json != expected { t.Fatalf("Expected %v, got %v", expected, json) } location, err := time.LoadLocation("Europe/Paris") if err != nil { t.Fatal(err) } aTime = time.Date(2015, 5, 29, 11, 1, 2, 3, location) json, err = FastMarshalJSON(aTime) if err != nil { t.Fatal(err) } expected = "\"2015-05-29T11:01:02.000000003+02:00\"" if json != expected { t.Fatalf("Expected %v, got %v", expected, json) } }
func (s Hourly) getTrigger() (time.Time, time.Time) { now := time.Now() loc, _ := time.LoadLocation("Local") trigger := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, loc) return trigger, now }
// Normalizes time format to one of two layouts (machine or human readable) // Checks if the time is valid and returns error if it is not // Parses in the location of Santiago func ReturnTimeString(humanReadable bool, d string, t string) (string, string, error) { const ( layoutHuman = "2/1/2006" layoutMachine = "2006-01-02" ) loc, err := time.LoadLocation("America/Santiago") if err != nil { return "", "", NewError(err, "Error de servidor", 500) } layout := returnTimeLayout(d) splits := strings.Split(t, ":") if len(splits) == 1 { if utf8.RuneCountInString(t) == 2 { layout += " 15" } else if utf8.RuneCountInString(t) == 1 { t = "0" + t layout += " 1" } else if utf8.RuneCountInString(t) == 4 { layout += " 1504" } } else if len(splits) == 2 { layout += " 15:04" } timeVar, err := time.ParseInLocation(layout, d+" "+t, loc) if err != nil { return "", "", NewError(nil, "Formato de tiempo invalido", 400) } if humanReadable { return timeVar.Format(layoutHuman), timeVar.Format("15:04"), nil } else { return timeVar.Format(layoutMachine), timeVar.Format("15:04"), nil } }
// Converts the post form variables into a slice of schedule blocks. func getScheduleBlocks(r *http.Request) ([]ScheduleBlock, error) { numScheduleBlocks, err := strconv.Atoi(r.PostFormValue("numScheduleBlocks")) if err != nil { return []ScheduleBlock{}, err } var returnErr error scheduleBlocks := make([]ScheduleBlock, numScheduleBlocks) location, _ := time.LoadLocation("Local") for i := 0; i < numScheduleBlocks; i++ { scheduleBlocks[i].StartTime, err = time.ParseInLocation("2006-01-02 03:04:05 PM", r.PostFormValue(fmt.Sprintf("startTime%d", i)), location) if err != nil { returnErr = err } scheduleBlocks[i].NumMatches, err = strconv.Atoi(r.PostFormValue(fmt.Sprintf("numMatches%d", i))) if err != nil { returnErr = err } scheduleBlocks[i].MatchSpacingSec, err = strconv.Atoi(r.PostFormValue(fmt.Sprintf("matchSpacingSec%d", i))) if err != nil { returnErr = err } } return scheduleBlocks, returnErr }
func updateReadme(t *testing.T, repo *Repository, content string) (*Oid, *Oid) { loc, err := time.LoadLocation("Europe/Berlin") checkFatal(t, err) sig := &Signature{ Name: "Rand Om Hacker", Email: "*****@*****.**", When: time.Date(2013, 03, 06, 14, 30, 0, 0, loc), } tmpfile := "README" err = ioutil.WriteFile(path.Join(path.Dir(path.Dir(repo.Path())), tmpfile), []byte(content), 0644) checkFatal(t, err) idx, err := repo.Index() checkFatal(t, err) err = idx.AddByPath("README") checkFatal(t, err) treeId, err := idx.WriteTree() checkFatal(t, err) currentBranch, err := repo.Head() checkFatal(t, err) currentTip, err := repo.LookupCommit(currentBranch.Target()) checkFatal(t, err) message := "This is a commit\n" tree, err := repo.LookupTree(treeId) checkFatal(t, err) commitId, err := repo.CreateCommit("HEAD", sig, sig, message, tree, currentTip) checkFatal(t, err) return commitId, treeId }