Example #1
0
File: gome.go Project: bamarni/gome
func vbbHandler(config *AppConfig, w http.ResponseWriter, r *http.Request) (interface{}, error) {
	depRequest := &vbb.Departure{
		StopId:    "A=1@O=Bersarinplatz (Berlin)@X=13452563@Y=52519341@U=86@L=009120516@B=1@V=3.9,@p=1449160158@",
		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
}
Example #2
0
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
}
Example #3
0
// 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
}
Example #4
0
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))
		}

	}
}
Example #5
0
// 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)
	}
}
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
}
Example #7
0
// 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
}
Example #8
0
File: guess.go Project: Feh/guess
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",
	}}
}
Example #9
0
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
}
Example #10
0
/* {{{ 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
}
Example #11
0
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
}
Example #12
0
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
}
Example #13
0
//类型转换
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)
}
Example #14
0
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)
	}
}
Example #15
0
// 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())
}
Example #16
0
func Save(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(r.FormValue("id"))
	start, _ := time.ParseInLocation("01/02/2006 03:04 pm", r.FormValue("startDate"), models.CentralTime)
	end, _ := time.ParseInLocation("01/02/2006 03:04 pm", r.FormValue("endDate"), models.CentralTime)
	newwindow, _ := strconv.ParseBool(r.FormValue("newWindow"))
	hash := r.URL.Fragment
	page := models.LandingPage{
		ID:              id,
		Name:            r.FormValue("name"),
		Start:           start,
		End:             end,
		URL:             r.FormValue("url"),
		NewWindow:       newwindow,
		MenuPosition:    r.FormValue("menuPosition"),
		Content:         r.FormValue("page_content"),
		LinkClasses:     r.FormValue("linkClasses"),
		ConversionID:    r.FormValue("conversionID"),
		ConversionLabel: r.FormValue("conversionLabel"),
	}
	urlstr := "/LandingPages/Edit/" + strconv.Itoa(page.ID)
	err := page.Save()
	if err != nil {
		urlstr += "?error=" + url.QueryEscape(err.Error())
	}
	if strings.TrimSpace(hash) != "" {
		urlstr += "#" + hash
	}
	http.Redirect(w, r, urlstr, http.StatusFound)
}
Example #17
0
func prepDate(d string) time.Time {
	loc, _ := time.LoadLocation("MSK")
	dd, d_err := time.ParseInLocation(time.RFC1123, d, loc)
	if d_err != nil {
		dd, _ = time.ParseInLocation(time.RFC1123Z, d, loc)
	}
	return dd
}
Example #18
0
func toAppropriateType(str string) (interface{}, rtype) {

	// 空
	if IsBlank(str) {
		return nil, nilValue
	} else {
		str = Trim(str)
	}

	regInt := regexp.MustCompile(REX_INT)
	if regInt.MatchString(str) {
		sint, err1 := strconv.Atoi(str)
		if err1 != nil {
			sint64, err2 := strconv.ParseInt(str, 10, 64)
			if err2 != nil {
				panic(err2)
			} else {
				return sint64, longRegion
			}
		} else {
			return sint, intRegion
		}
	}
	regFloat := regexp.MustCompile(REX_FLOAT)
	if regFloat.MatchString(str) {
		sfloat, err1 := strconv.ParseFloat(str, 32)
		if err1 != nil {
			sfloat64, err2 := strconv.ParseFloat(str, 64)
			if err2 != nil {
				panic(err2)
			} else {
				return sfloat64, float64Region
			}
		} else {
			return float32(sfloat), floatRegion
		}
	}
	regDateTime := regexp.MustCompile(REX_DATE_TIME)
	if regDateTime.MatchString(str) {
		sdatetime, err1 := time.ParseInLocation("2006-01-02 15:04:05", TrimExtraSpace(str), time.Local)
		if err1 != nil {
			panic(err1)
		} else {
			return sdatetime, dateRegion
		}
	}
	regDate := regexp.MustCompile(REX_DATE)
	if regDate.MatchString(str) {
		sdate, err1 := time.ParseInLocation("2006-01-02", str, time.Local)
		if err1 != nil {
			panic(err1)
		} else {
			return sdate, dateRegion
		}
	}
	// 没有可以匹配的?
	panic(errors.New("not a region appropriate type, " + str))
}
Example #19
0
File: crawl.go Project: daizong/xyz
func readLastCrawlTime() {
	b, _ := ioutil.ReadFile(filepath.Join(jsonPath, "lastPubDate.txt"))
	if len(b) == 0 {
		crawStartTime := config.Get("CrawlStartTime").(string)
		lastPubTime, _ = time.ParseInLocation("2006-01-02 15:04:05 +0800 CST", crawStartTime, time.Local)
	} else {
		lastPubTime, _ = time.ParseInLocation("2006-01-02 15:04:05 +0800 CST", string(b), time.Local)
	}
}
Example #20
0
func detectAnomalyes(start, end, metric string, period int) ([]chartData, []anomalyData, error) {
	loc, _ := time.LoadLocation("Asia/Novosibirsk")
	startTime, err := time.ParseInLocation("2006/01/02-15:04:05", start, loc)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to parse start date: %v", err)
	}
	endTime, err := time.ParseInLocation("2006/01/02-15:04:05", end, loc)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to parse end date: %v", err)
	}

	dps, err := getDataPoints(tsdbHost, metric, startTime, endTime)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to get data from tsdb: %v", err)
	}

	var movingAverage float64
	var sigma float64
	vals := make([]float64, period)

	chart := make([]chartData, 0)
	anomalyes := make([]anomalyData, 0)

	for idx, cdp := range dps {
		if idx <= period {
			continue
		}
		points := dps[idx-period : idx]
		for i, dp := range points {
			vals[i] = dp.Value
		}

		movingAverage = average(vals)
		sigma = test3Sigma(vals)
		anomalyIdx := 0
		if sigma > 1.2 {
			anomalyIdx++
			anomalyes = append(anomalyes, anomalyData{
				ID:        fmt.Sprintf("anomaly-%d", anomalyIdx),
				Date:      cdp.Time.In(loc).Format("2006-01-02 15:04:05"),
				Alpha:     0.5,
				Color:     "#FF0000",
				Thickness: 5,
			})
		}
		//fmt.Printf("%v,%v,%v,%v\n", cdp.Time.Format("2006-01-02 15:04:05"), cdp.Value, movingAverage, sigma)

		chart = append(chart, chartData{
			cdp.Time.In(loc).Format("2006-01-02 15:04:05"),
			cdp.Value,
			movingAverage,
			sigma,
		})
	}

	return chart, anomalyes, nil
}
Example #21
0
// return how many seconds time zone difference there is between the current location and
// Pacific Time Zone
func secondsFromPST(t *testing.T) int64 {
	pst, err := time.LoadLocation("America/Los_Angeles")
	assert.NoError(t, err)
	timeHere, err := time.ParseInLocation(time.ANSIC, "Mon Jan 2 15:04:05 2006", time.Now().Location())
	assert.NoError(t, err)
	timePST, err := time.ParseInLocation(time.ANSIC, "Mon Jan  2 15:04:05 2006", pst)
	assert.NoError(t, err)
	return int64(timeHere.Sub(timePST).Seconds())
}
Example #22
0
func ParseTimeDetectLayout(tmStr string, timezone string) (time.Time, error) {
	tmStr = strings.TrimSpace(tmStr)
	var nilTime time.Time
	if len(tmStr) == 0 || tmStr == UNLIMITED {
		return nilTime, nil
	}
	loc, err := time.LoadLocation(timezone)
	if err != nil {
		return nilTime, err
	}
	rfc3339Rule := regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.+$`)
	sqlRule := regexp.MustCompile(`^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$`)
	gotimeRule := regexp.MustCompile(`^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.?\d*\s[+,-]\d+\s\w+$`)
	fsTimestamp := regexp.MustCompile(`^\d{16}$`)
	astTimestamp := regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d*[+,-]\d+$`)
	unixTimestampRule := regexp.MustCompile(`^\d{10}$`)
	oneLineTimestampRule := regexp.MustCompile(`^\d{14}$`)
	oneSpaceTimestampRule := regexp.MustCompile(`^\d{2}\.\d{2}.\d{4}\s{1}\d{2}:\d{2}:\d{2}$`)
	eamonTimestampRule := regexp.MustCompile(`^\d{2}/\d{2}/\d{4}\s{1}\d{2}:\d{2}:\d{2}$`)
	broadsoftTimestampRule := regexp.MustCompile(`^\d{14}\.\d{3}`)
	switch {
	case astTimestamp.MatchString(tmStr):
		return time.Parse("2006-01-02T15:04:05.999999999-0700", tmStr)
	case rfc3339Rule.MatchString(tmStr):
		return time.Parse(time.RFC3339, tmStr)
	case gotimeRule.MatchString(tmStr):
		return time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", tmStr)
	case sqlRule.MatchString(tmStr):
		return time.ParseInLocation("2006-01-02 15:04:05", tmStr, loc)
	case fsTimestamp.MatchString(tmStr):
		if tmstmp, err := strconv.ParseInt(tmStr+"000", 10, 64); err != nil {
			return nilTime, err
		} else {
			return time.Unix(0, tmstmp).In(loc), nil
		}
	case unixTimestampRule.MatchString(tmStr):
		if tmstmp, err := strconv.ParseInt(tmStr, 10, 64); err != nil {
			return nilTime, err
		} else {
			return time.Unix(tmstmp, 0).In(loc), nil
		}
	case tmStr == "0" || len(tmStr) == 0: // Time probably missing from request
		return nilTime, nil
	case oneLineTimestampRule.MatchString(tmStr):
		return time.ParseInLocation("20060102150405", tmStr, loc)
	case oneSpaceTimestampRule.MatchString(tmStr):
		return time.ParseInLocation("02.01.2006  15:04:05", tmStr, loc)
	case eamonTimestampRule.MatchString(tmStr):
		return time.ParseInLocation("02/01/2006 15:04:05", tmStr, loc)
	case broadsoftTimestampRule.MatchString(tmStr):
		return time.ParseInLocation("20060102150405.999", tmStr, loc)
	case tmStr == "*now":
		return time.Now(), nil
	}
	return nilTime, errors.New("Unsupported time format")
}
Example #23
0
func (t *TimeStamp) ParseInLocation(createdat, updatedat string) error {
	var err error
	if createdat != "" {
		t.CreatedAt, err = time.ParseInLocation(Format, createdat, Location)
	}
	if updatedat != "" {
		t.UpdatedAt, err = time.ParseInLocation(Format, updatedat, Location)
	}
	return err
}
Example #24
0
func populate() {
	loc, _ := time.LoadLocation(timezone)

	for k, v := range _callTime {
		iftar, _ := time.ParseInLocation(timeFormatLong, fmt.Sprintf("%v %v", k, v.iftar), loc)
		sahur, _ := time.ParseInLocation(timeFormatLong, fmt.Sprintf("%v %v", k, v.sahur), loc)

		callTime[k] = timePair{iftar, sahur}
	}
}
Example #25
0
// Parse date by std date string
func ParseDate(dateStr string) time.Time {
	date, err := time.ParseInLocation(fmt.Sprintf(DATE_FORMAT), dateStr, time.Now().Location())
	if err != nil {
		date, err = time.ParseInLocation(fmt.Sprintf(DATE_FORMAT_WITH_TIMEZONE), dateStr, time.Now().Location())
		if err != nil {
			Fatal(err.Error())
		}
	}
	return date.Local()
}
Example #26
0
func (t *messageHeaderTime) UnmarshalText(data []byte) error {
	g, err := time.ParseInLocation(messageHeaderTimeFormat, string(data), time.UTC)
	if err != nil {
		g, err = time.ParseInLocation(messageHeaderTimeFormatZ, string(data), time.UTC)
		if err != nil {
			return err
		}
	}
	*t = messageHeaderTime{g}
	return nil
}
Example #27
0
func main() {

	// Pointers for command line flags/arguments
	actionPtr := flag.String("action", "add", "Allows adding, removing, updating tasks")
	namePtr := flag.String("name", "Undefined", "Name of the task")
	commTypePtr := flag.String("type", "Message", "Type of command")
	commandPtr := flag.String("command", "Undefined", "Command to be executed")
	startPtr := flag.String("start", "Undefined", "Start time")
	endPtr := flag.String("end", "Undefined", "End time")
	periodPtr := flag.String("period", "None", "Period of the task")

	// Parsing the command line flags/arguments
	flag.Parse()

	// Opening the taskfile
	file, err := os.OpenFile(".taskfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)

	// Check for errors in opening the file
	if err != nil {
		fmt.Println("Error in opening file.")
		log.Fatal(err)
	}

	// Make sure the file is closed after main function ends
	defer file.Close()

	// Switch chooses the action according to the action flag
	switch *actionPtr {
	case "add":

		// Check that start time is in correct format
		if _, err := time.ParseInLocation(timeFormat, *startPtr, location); err != nil {
			fmt.Println("Invalid format for start time")
			return
		}

		// Check that end time is in correct format
		if _, err := time.ParseInLocation(timeFormat, *endPtr, location); err != nil {
			fmt.Println("Invalid format for end time")
			return
		}

		//Adding task to the file
		strToWrite := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\n", *namePtr, *commTypePtr, *commandPtr, *startPtr, *endPtr, *periodPtr)

		if _, err := file.WriteString(strToWrite); err != nil {
			fmt.Println("Error in writing to file")
			log.Fatal(err)
		}
	// TODO: Add delete and update functionality
	default:
		fmt.Println("Invalid action")
	}
}
Example #28
0
// ParseContent implements Crawler#ParseContent()
func (c *IEPGDataCrawler) ParseContent(r io.Reader) (*crawler.Result, error) {
	var err error
	iepg := &pt.IEPG{}
	iepg.Body = make([]byte, 0)
	rio := transform.NewReader(r, japanese.ShiftJIS.NewDecoder())
	scanner := bufio.NewScanner(rio)
	kv := make(map[string]string)
	for scanner.Scan() {
		line := scanner.Text()
		if line == "" {
			for scanner.Scan() {
				line = scanner.Text()
				iepg.Body = append(iepg.Body, []byte(line)...)
			}
			break
		}
		tmp := strings.Split(line, ": ")
		if len(tmp) != 2 {
			continue
		}
		kv[tmp[0]] = tmp[1]
	}
	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("IEPG scan error: %v", err)
	}
	iepg.StationID = kv["station"]
	iepg.StationName = kv["station-name"]
	iepg.ProgramTitle = kv["program-title"]
	iepg.Source = pt.IEPGSourceCrawler
	if iepg.StationID == "" {
		return nil, errMissingStationID
	}
	if kv["program-id"] != "" {
		if iepg.ProgramID, err = strconv.Atoi(kv["program-id"]); err != nil {
			return nil, fmt.Errorf("Could not parse `program-id` - %q in %v: %v ", kv["program-id"], kv, err)
		}
	}
	startAt := fmt.Sprintf("%s-%s-%sT%s:00", kv["year"], kv["month"], kv["date"], kv["start"])
	if iepg.StartAt, err = time.ParseInLocation(iepgTimeFormat, startAt, iepgTimeLocation); err != nil {
		return nil, fmt.Errorf("Could not parse start time - %q in %v: %v", startAt, kv, err)
	}
	endAt := fmt.Sprintf("%s-%s-%sT%s:00", kv["year"], kv["month"], kv["date"], kv["end"])
	if iepg.EndAt, err = time.ParseInLocation(iepgTimeFormat, endAt, iepgTimeLocation); err != nil {
		return nil, fmt.Errorf("Could not parse end time - %q in %v: %v", endAt, kv, err)
	}
	if iepg.EndAt.Before(iepg.StartAt) {
		iepg.EndAt = iepg.EndAt.AddDate(0, 0, 1)
	}
	return &crawler.Result{
		Data: iepg,
		Next: "",
	}, nil
}
Example #29
0
func (it *Time) UnmarshalJSON(data []byte) error {
	t, err := time.ParseInLocation(jsonFormat, string(data), fixedZone)
	if err == nil {
		*it = Time(t)
	} else {
		t, err = time.ParseInLocation(jsonFormat2, string(data), fixedZone)
		if err == nil {
			*it = Time(t)
		}
	}

	return err
}
Example #30
0
func main() {
	var host = flag.String("host", "", "Server listen host, default 0.0.0.0")
	var port = flag.Int("port", 80, "Server listen port, default 80")
	var url = flag.String("url", "", "Click open url")
	var nst = flag.String("nst", "", "Notify start time, format: YYYY-mm-dd HH:MM")
	var nvt = flag.String("nvt", "", "Notify over time, format as start time")
	var cpu = flag.Int("cpu", 0, "Go runtime max process")
	var logpath = flag.String("logpath", "./", "Log path")
	var logfile = flag.String("logfile", "", "Log filename")
	var nextmin = flag.Int("nextmin", NextMinute, "Next request duration(minute)")
	flag.Parse()
	if *logfile != "" {
		if logger, err := logging.NewHourRotationLogger(*logfile, *logpath, LOGFILE_SUFFIX); err != nil {
			panic(err)
		} else {
			logging.SetDefaultLogger(logger)
			logging.SetPrefix("BWService")
		}
	}
	if *cpu > 0 {
		runtime.GOMAXPROCS(*cpu)
	}
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		panic(err)
	}
	if t, err := time.ParseInLocation("2006-01-02 15:04", *nst, loc); err != nil {
		panic(err)
	} else {
		NotifyStartTime = t
	}
	if t, err := time.ParseInLocation("2006-01-02 15:04", *nvt, loc); err != nil {
		panic(err)
	} else {
		NotifyEndTime = t
	}
	if *url == "" {
		panic(*url)
	} else {
		ClickURL = *url
	}
	if *nextmin > 0 {
		NextMinute = *nextmin
	}
	var addr = net.JoinHostPort(*host, strconv.Itoa(*port))
	http.HandleFunc("/patrol", Patrol)
	logging.Info("[%s] (%s) - (%s) => %s, %d\n", addr, NotifyStartTime.String(), NotifyEndTime.String(), ClickURL, NextMinute)
	if err := http.ListenAndServe(addr, nil); err != nil {
		logging.Error("%s", err.Error())
	}
}