本文整理汇总了Golang中Time.ParseInLocation函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseInLocation函数的具体用法?Golang ParseInLocation怎么用?Golang ParseInLocation使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseInLocation函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: vbbHandler
func vbbHandler(config *AppConfig, w http.ResponseWriter, r *http.Request) (interface{}, error) {
depRequest := &vbb.Departure{
StopId: "[email protected]=Bersarinplatz (Berlin)@[email protected][email protected][email protected][email protected][email protected]=3.9,@[email protected]",
Direction: "9120004",
}
depBoard, err := config.Vbb.GetDepartureBoard(depRequest)
if err != nil {
return nil, err
}
loc, _ := time.LoadLocation(config.Location)
timeLayout := "2006-01-02 15:04:05"
var deps []Departure
for _, dep := range depBoard.Departures[0:3] {
Time, _ := time.ParseInLocation(timeLayout, dep.Date+" "+dep.Time, loc)
realTime, _ := time.ParseInLocation(timeLayout, dep.RtDate+" "+dep.RtTime, loc)
delay := realTime.Sub(Time).Minutes()
dep := Departure{Time.Format("15:04"), int(delay)}
deps = append(deps, dep)
}
return deps, nil
}
示例2: ParseSchedule
func ParseSchedule(s string) (c Schedule, err error) {
elems := strings.Split(s, " ")
switch len(elems) {
case 6: // Everything specified
_end := elems[4] + " " + elems[5]
if c.End, err = time.ParseInLocation(timefmt, _end[1:], time.UTC); err != nil {
return
}
fallthrough
case 4: // start time and frequency
var count uint64
if count, err = strconv.ParseUint(elems[2][1:], 10, 32); err != nil {
return
}
c.Freq.Count = uint(count)
var ok bool
if c.Freq.Unit, ok = tuLookup[elems[3]]; !ok {
err = fmt.Errorf("Unknown timeunit %s", elems[3])
return
}
fallthrough
case 2: // Only start time
if c.Start, err = time.ParseInLocation(timefmt, elems[0]+" "+elems[1], time.UTC); err != nil {
return
}
default:
err = errors.New("Unknown schedule format")
}
return
}
示例3: UnmarshalJSON
// UnmarshalJSON deserializes the ISO6801Time from JSON string
func (it *ISO6801Time) UnmarshalJSON(data []byte) error {
str := string(data)
if str == "\"\"" || len(data) == 0 {
return nil
}
var t time.Time
var err error
if str[0] == '"' {
t, err = time.ParseInLocation(jsonFormatISO8601, str, time.UTC)
if err != nil {
t, err = time.ParseInLocation(jsonFormatISO8601withoutSeconds, str, time.UTC)
}
} else {
var i int64
i, err = strconv.ParseInt(str, 10, 64)
if err == nil {
t = time.Unix(i/1000, i%1000)
}
}
if err == nil {
*it = ISO6801Time(t)
}
return err
}
示例4: TestData
func TestData(t *testing.T) {
for _, datum := range DATA {
if loc, err := time.LoadLocation(datum.location.timezone); err != nil {
t.Fatalf("bad location %s", datum.location.timezone)
} else {
formatted := fmt.Sprintf("%s 00:00:00", datum.times.date)
midnight, err := time.ParseInLocation("2006-01-02 15:04:05", formatted, loc)
if err != nil {
t.Fatalf("failed to parse date/timestamp '%s': %s", formatted, err)
}
checkDate := func(description string, timeOfDay string, calculated time.Time) {
formatted := fmt.Sprintf("%s %s", datum.times.date, timeOfDay)
timestamp, err := time.ParseInLocation("2006-01-02 15:04", formatted, loc)
if err != nil {
t.Fatalf("failed to parse date/timestamp '%s': %s", formatted, err)
}
actualError := math.Abs((float64)(timestamp.Sub(calculated)))
if actualError > float64(datum.error) {
t.Errorf("calculated -> %v, wanted -> %v %d -> (wanted < %d). location=%s date=%s", calculated, timestamp, actualError, datum.error, datum.location.timezone, datum.times.date)
}
}
checkDate("dawn", datum.times.dawn, NextDawn(midnight, datum.location.latitude, datum.location.longitude, CIVIL_DAWN))
checkDate("sunrise", datum.times.sunrise, NextSunrise(midnight, datum.location.latitude, datum.location.longitude))
checkDate("sunset", datum.times.sunset, NextSunset(midnight, datum.location.latitude, datum.location.longitude))
checkDate("dusk", datum.times.dusk, NextDusk(midnight, datum.location.latitude, datum.location.longitude, CIVIL_DUSK))
}
}
}
示例5: seedTestDB
// seedTestDB will seed the db every second betwene the given times
func seedTestDB(dal *DAL, ip, startTime, endTime string) {
const tfmt = "01/02/06 03:04:05 pm"
db, err := bolt.Open(dal.fileName, 0600, nil)
defer db.Close()
if err != nil {
log.Fatal(err)
}
maxRes, minRes := float32(1500.0), float32(5.0)
rand.Seed(time.Now().UnixNano())
start, _ := time.ParseInLocation(tfmt, startTime, time.UTC)
end, _ := time.ParseInLocation(tfmt, endTime, time.UTC)
err = db.Update(func(tx *bolt.Tx) error {
// pt == ping timestamp
for pt := start; pt.Sub(end) != 0; pt = pt.Add(1 * time.Second) {
resTime := rand.Float32()*(maxRes-minRes) + minRes
err := dal.SavePingWithTransaction(ip, pt, resTime, tx)
if err != nil {
return err
}
}
return nil
})
if err != nil {
log.Fatal(err)
}
}
示例6: Process
func (c *AddBirthdayCommand) Process(args []string, msg *discordgo.Message, info *GuildInfo) (string, bool) {
if len(args) < 2 {
return "```You must first ping the member and then provide the date!```", false
}
ping := StripPing(args[0])
arg := strings.Join(args[1:], " ") + " " + strconv.Itoa(time.Now().Year())
t, err := time.ParseInLocation("_2 Jan 2006", arg, getTimezone(info, nil)) // Deliberately do not include the user timezone here. We want this to operate on the server timezone.
if err != nil {
t, err = time.ParseInLocation("Jan _2 2006", arg, getTimezone(info, nil))
}
t = t.UTC()
if err != nil {
return "```Error: Could not parse time! Make sure it's in the format \"2 Jan\"```", false
}
for t.Before(time.Now().AddDate(0, 0, -1).UTC()) {
t = t.AddDate(1, 0, 0)
}
_, err = strconv.ParseUint(ping, 10, 64)
if len(ping) == 0 || err != nil {
return "```Error: Invalid ping for member! Make sure you actually ping them via @MemberName, don't just type the name in.```", false
}
sb.db.AddScheduleRepeat(SBatoi(info.Guild.ID), t, 8, 1, 1, ping) // Create the normal birthday event at 12 AM on this server's timezone
if !sb.db.AddScheduleRepeat(SBatoi(info.Guild.ID), t.AddDate(0, 0, 1), 8, 1, 4, ping) { // Create the hidden "remove birthday role" event 24 hours later.
return "```Error: servers can't have more than 5000 events!```", false
}
return ReplaceAllMentions("```Added a birthday for <@" + ping + ">```"), false
}
示例7: ParseTimestamp
// ParseTimestamp parses the timestamp.
func (ctx EvalContext) ParseTimestamp(s DString) (DTimestamp, error) {
str := string(s)
t, err := time.Parse(dateFormat, str)
if err == nil {
return DTimestamp{Time: t}, nil
}
if t, err = time.Parse(TimestampWithOffsetZoneFormat, str); err == nil {
t = t.UTC()
return DTimestamp{Time: t}, nil
}
location := time.UTC
if ctx.GetLocation != nil {
if location, err = ctx.GetLocation(); err != nil {
return DummyTimestamp, err
}
}
if t, err = time.ParseInLocation(timestampFormat, str, location); err == nil {
t = t.UTC()
return DTimestamp{Time: t}, nil
}
if t, err = time.ParseInLocation(timestampWithNamedZoneFormat, str, location); err == nil {
t = t.UTC()
return DTimestamp{Time: t}, nil
}
// Parse other formats in the future.
return DummyTimestamp, err
}
示例8: 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",
}}
}
示例9: ConvertCSVRecords
func ConvertCSVRecords(r io.Reader, project string) ([]TimeRecord, error) {
res := []TimeRecord{}
csvReader := csv.NewReader(r)
records, err := csvReader.ReadAll()
if err != nil {
return res, err
}
for _, record := range records {
if len(record) < 5 {
continue
}
date, err := time.ParseInLocation(CSVDateFormat, record[CSVDateIndex], time.Local)
if err != nil {
continue
}
begin, err := time.ParseInLocation(CSVTimeFormat, record[CSVBeginIndex], time.Local)
if err != nil {
continue
}
end, err := time.ParseInLocation(CSVTimeFormat, record[CSVEndIndex], time.Local)
if err != nil {
continue
}
message := record[CSVMessageIndex]
rec := NewTimeRecord()
rec.Begin = begin
rec.Notes = message
rec.Project = project
rec.SetEnd(end)
rec.SetDate(date)
res = append(res, rec)
}
return res, nil
}
示例10: setTimeRangeFromDate
/* {{{ func (rc *RESTContext) setTimeRangeFromDate(p []string) {
* 时间段信息
*/
func (rc *RESTContext) setTimeRangeFromDate(p []string) {
tr := new(TimeRange)
rc.SetEnv(TimeRangeKey, tr)
var s, e, format string
if len(p) > 1 { //有多个,第一个是start, 第二个是end, 其余忽略
s, e = p[0], p[1]
} else if len(p) > 0 { //只有一个, 可通过 "{start},{end}"方式传
pieces := strings.SplitN(p[0], ",", 2)
s = pieces[0]
if len(pieces) > 1 {
e = pieces[1]
}
}
if len(s) == len(_DATE_FORM) {
format = _DATE_FORM
} else if len(s) == len(_DATE_FORM1) {
format = _DATE_FORM1
}
if ts, err := time.ParseInLocation(format, s, Env().Location); err == nil {
tr.Start = ts
dura, _ := time.ParseDuration("86399s") // 一天少一秒
tr.End = ts.Add(dura) //当天的最后一秒
//只有成功获取了start, end才有意义
if t, err := time.ParseInLocation(format, e, Env().Location); err == nil {
te := t.Add(dura)
if te.After(ts) { //必须比开始大
tr.End = te
}
}
}
return
}
示例11: mergeDateTime
func mergeDateTime(tm, dt string) *time.Time {
reTm := time.Now().Add(createTaskNowPad)
if dt == "" && tm == "" {
return nil
}
if dt != "" {
t, err := time.Parse(dateParseFormat, dt)
if err != nil {
fmt.Printf("Error creating task:\n%v\n", err)
os.Exit(1)
}
reTm = t
}
if tm != "" {
_, err := time.ParseInLocation(timeParseFormat, tm, time.Local)
if err != nil {
fmt.Printf("Error creating task:\n%v\n", err)
os.Exit(1)
}
reTm, err = time.ParseInLocation(unionParseFormat, fmt.Sprintf("%s %s", tm, reTm.Format(dateParseFormat)), time.Local)
if err != nil {
fmt.Printf("Error creating task:\n%v\n", err)
os.Exit(1)
}
}
return &reTm
}
示例12: GetTimeInLocationOk
func (p *Params) GetTimeInLocationOk(key string, loc *time.Location) (time.Time, bool) {
val, ok := p.Get(key)
if !ok {
return time.Time{}, false
}
if t, ok := val.(time.Time); ok {
return t, true
}
if str, ok := val.(string); ok {
if t, err := time.ParseInLocation(time.RFC3339, str, loc); err == nil {
return t, true
}
if t, err := time.ParseInLocation(DateOnly, str, loc); err == nil {
return t, true
}
if t, err := time.ParseInLocation(DateTime, str, loc); err == nil {
return t, true
}
if t, err := time.ParseInLocation(HTMLDateTimeLocal, str, loc); err == nil {
return t, true
}
}
return time.Time{}, false
}
示例13: TypeConversion
//类型转换
func TypeConversion(value string, ntype string) (reflect.Value, error) {
if ntype == "string" {
return reflect.ValueOf(value), nil
} else if ntype == "time.Time" {
t, err := time.ParseInLocation("2006-01-02 15:04:05", value, time.Local)
return reflect.ValueOf(t), err
} else if ntype == "Time" {
t, err := time.ParseInLocation("2006-01-02 15:04:05", value, time.Local)
return reflect.ValueOf(t), err
} else if ntype == "int" {
i, err := strconv.Atoi(value)
return reflect.ValueOf(i), err
} else if ntype == "int8" {
i, err := strconv.ParseInt(value, 10, 64)
return reflect.ValueOf(int8(i)), err
} else if ntype == "int32" {
i, err := strconv.ParseInt(value, 10, 64)
return reflect.ValueOf(int64(i)), err
} else if ntype == "int64" {
i, err := strconv.ParseInt(value, 10, 64)
return reflect.ValueOf(i), err
} else if ntype == "float32" {
i, err := strconv.ParseFloat(value, 64)
return reflect.ValueOf(float32(i)), err
} else if ntype == "float64" {
i, err := strconv.ParseFloat(value, 64)
return reflect.ValueOf(i), err
} else if ntype == "slice" {
i := []byte(value)
return reflect.ValueOf(i), nil
}
//else if .......增加其他一些类型的转换
return reflect.ValueOf(value), errors.New("未知的类型:" + ntype)
}
示例14: TestArchiveFilenamesDifferAcrossDST
func TestArchiveFilenamesDifferAcrossDST(t *testing.T) {
loc, _ := time.LoadLocation("America/Los_Angeles")
// hourly across DST start
t1, _ := time.ParseInLocation(time.RFC822, "09 Mar 14 01:00 PST", loc)
t2 := calculateNextRollTime(t1, RollHourly)
f1 := generateArchiveFilename("foo.log", t1, RollHourly)
f2 := generateArchiveFilename("foo.log", t2, RollHourly)
if f1 == f2 {
t.Errorf("filenames should differ across DST start")
}
if f2 != "foo.log.2014-03-09-03-00-PDT" {
t.Errorf("expected filename 'foo.log.2014-03-09-03-00-PDT' but got %s", f2)
}
// hourly across DST end
t1, _ = time.ParseInLocation(time.RFC822, "02 Nov 14 01:00 PDT", loc)
t2 = calculateNextRollTime(t1, RollHourly)
f1 = generateArchiveFilename("foo.log", t1, RollHourly)
f2 = generateArchiveFilename("foo.log", t2, RollHourly)
if f1 == f2 {
t.Errorf("filenames should differ across DST end")
}
if f2 != "foo.log.2014-11-02-01-00-PST" {
t.Errorf("expected filename 'foo.log.2014-03-09-03-00-PDT' but got %s", f2)
}
}
示例15: main
// A small programme written to get some understanding of how time zone handling is done in Go.
func main() {
// Input, perhaps from user via an HTML form or some other means
fromStr := "2013-07-09"
toStr := "2013-11-10" // 24 hours will be added to this date below to make it exclusive (eg. include all day!)
locationStr := "Europe/Copenhagen"
// Get location, fall back to UTC
location, err := time.LoadLocation(locationStr)
if err != nil {
location = time.UTC
}
// Parse dates, fall back to today for both dates if necessary
from, err := time.ParseInLocation("2006-01-02", fromStr, location)
if err != nil {
fmt.Printf("Unable to parse from-date '%v'\n", fromStr)
from, _ = time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), location)
}
to, err := time.ParseInLocation("2006-01-02", toStr, location)
if err != nil {
fmt.Printf("Unable to parse to date '%v'\n", toStr)
to, _ = time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), location)
}
// Want all day of "to" - so add 24 hours and use it as exclusive when doing database queries for example.
to = to.Add(24 * time.Hour)
fmt.Printf("%11s %v\n%11s %v\n%11s %v.\n", "Period from", from, "to", to, "in", location)
fmt.Printf("Notice offset. Daylight saving time means that %v can be either %v or %v.\n", location, from.Format("-0700"), to.Format("-0700"))
fmt.Printf("In UTC these dates are from '%v' to '%v' which is useful for querying databases that stores dates in UTC.\n", from.UTC(), to.UTC())
}