本文整理汇总了Golang中Time.LoadLocation函数的典型用法代码示例。如果您正苦于以下问题:Golang LoadLocation函数的具体用法?Golang LoadLocation怎么用?Golang LoadLocation使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了LoadLocation函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: loadZone
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
}
示例2: TestTime
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))
}
示例3: SetTimeLocation
//设置时区,参数错误则使用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())
}
}
示例4: PostComments
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)
}
}
示例5: Index
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)
}
}
示例6: init
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)
}
})
}
示例7: TestEqual
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")
}
}
示例8: 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)
}
}
}
}
示例9: init
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)
}
示例10: getDateForRegion
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)
}
}
示例11: TimeZone
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
}
示例12: GetWeather
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)
}
}
示例13: TestTimezone
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")
}
示例14: main
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())
}
示例15: init
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")
}
}