Exemple #1
0
// Times returns the start and stop time for
// the closest Day translation to now.
func (d *Day) Times(now time.Time) (closestStart time.Time, closestStop time.Time) {
	if now.IsZero() {
		Log.Error("Cannot find times without reference")
		return
	}

	if loc, err := d.GetLocation(); loc != nil && err == nil {
		now = now.In(loc)
	}

	// find nearest start time of this slot
	if now.Weekday() == d.Day && todayAt(now, d.Start).Before(now) {
		// if the schedule is for today
		// and we are after that scheduled time,
		// then we have found the closest start
		closestStart = todayAt(now, d.Start)
	} else {
		// Step back a day at a time until we find
		// the most recent day that matches the day
		// of the week of our Day.
		for i := 1; i < 8; i++ {
			sTime := now.Add(-time.Duration(i) * 24 * time.Hour)
			if sTime.Weekday() == d.Day {
				closestStart = todayAt(sTime, d.Start)
				break
			}
		}
	}

	// closestStop is just the closests start plus
	// the duration
	closestStop = closestStart.Add(d.Duration)

	return
}
Exemple #2
0
func main() {
	flagutil.Usage = "[seconds]"
	flag.Parse()

	var t time.Time

	// Get our time.
	switch flag.NArg() {
	case 0:
		t = time.Now()
	case 1:
		sec, err := strconv.ParseInt(flag.Arg(0), 10, 64)
		if err != nil {
			log.Fatal(err)
		}
		t = time.Unix(sec, 0)
	default:
		log.Fatal("bad args")
	}

	// Get our timezone.
	if *utc {
		t = t.In(time.UTC)
	}

	// Print the time.
	if *epoch {
		fmt.Println(t.Unix())
	} else {
		fmt.Println(t.Format(time.UnixDate))
	}
}
Exemple #3
0
// ActiveAt says whether the given time is
// wihtin the schedule of this Day schedule.
func (d *Day) ActiveAt(t time.Time) bool {
	if loc, err := d.GetLocation(); loc != nil && err == nil {
		t = t.In(loc)
	}
	start, stop := d.Times(t)
	return t.After(start) && t.Before(stop)
}
Exemple #4
0
func differentTZs(t time.Time) []string {
	var lines []string
	for _, loc := range TZs {
		lines = append(lines, fmt.Sprintf("%s (%s)", t.In(loc).String(), loc.String()))
	}
	return lines
}
Exemple #5
0
// FindRecentlyOpened 回傳最近一個開市時間(UTC 0)
func FindRecentlyOpened(date time.Time) time.Time {
	var (
		d     = date.In(utils.TaipeiTimeZone)
		days  = d.Day()
		index int
		tp    *TimePeriod
	)

	for {
		if IsOpen(d.Year(), d.Month(), days) {
			if index == 0 {
				tp = NewTimePeriod(time.Date(d.Year(), d.Month(), days, d.Hour(), d.Minute(), d.Second(), d.Nanosecond(), utils.TaipeiTimeZone))
				if tp.AtBefore() || tp.AtOpen() {
					days--
					for {
						if IsOpen(d.Year(), d.Month(), days) {
							break
						}
						days--
					}
				}
			}
			return time.Date(d.Year(), d.Month(), days, 0, 0, 0, 0, time.UTC)
		}
		days--
		index++
	}

}
Exemple #6
0
func (*simpleFormatter) Format(level loggo.Level, module string, timestamp time.Time, message string) string {
	ts := timestamp.In(time.UTC).Format("2006-01-02 15:04:05")
	// Just show the last element of the module.
	lastDot := strings.LastIndex(module, ".")
	module = module[lastDot+1:]
	return fmt.Sprintf("%s %s %s %s", ts, level, module, message)
}
Exemple #7
0
func main() {
	flag.Parse()

	var t time.Time
	var err error
	if timedate == "" {
		t = time.Now()
	} else {
		t, err = time.Parse(time.RFC1123, timedate)
		if err != nil {
			fmt.Println(err)
			return
		}
	}

	zones := strings.Split(timezones, ",")

	fmt.Println(t.Format(time.RFC1123), "(Origin)")
	for _, zone := range zones {
		loc, err := time.LoadLocation(zone)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(t.In(loc).Format(time.RFC1123))
	}
}
Exemple #8
0
func (notifier *Notify) Notify(name string, url string, lastChecked time.Time, template string, code int, responseTime float64) {
	ssettings := Setting{}
	serversettings, err := ssettings.Get()
	if err != nil {
		log.Println(err)
		return
	}
	settings := Settings{
		Server:   serversettings.Server,
		Email:    serversettings.Email,
		SSL:      serversettings.SSL,
		Username: serversettings.Username,
		Password: serversettings.Password,
		Port:     serversettings.Port,
	}
	layout := "Mon, 01/02/06, 3:04PM MST"
	Local, _ := time.LoadLocation("US/Central")
	localChecked := lastChecked.In(Local).Format(layout)

	var tos []string
	var subject string
	var body string

	if template == "up" {
		tos = []string{notifier.Email}
		subject = name + " Site Restored Notification"
		body = "<html><body><p>Hello " + notifier.Name + "</p><p>The " + name + " website at " + url + " is restored as of " + localChecked + ".</p></body></html>"
	} else {
		tos = []string{notifier.Email}
		subject = name + " Site Outage Warning!"
		body = "<html><body><p>Hello " + notifier.Name + "</p><p>The " + name + " website at " + url + " is down as of " + localChecked + ". It responded with an error code of " + strconv.Itoa(code) + " and a response time of " + strconv.FormatFloat(responseTime, 'g', -1, 64) + " ms.</p></body></html>"
	}
	Send(settings, tos, subject, body, true)
}
Exemple #9
0
// ParseTimestamp parses the timestamp.
func (ctx EvalContext) ParseTimestamp(s DString) (DTimestamp, error) {
	loc := time.UTC
	if ctx.GetLocation != nil {
		var err error
		if loc, err = ctx.GetLocation(); err != nil {
			return DummyTimestamp, err
		}
	}

	str := string(s)
	var err error

	for _, format := range []string{
		dateFormat,
		TimestampWithOffsetZoneFormat,
		timestampFormat,
		timestampWithNamedZoneFormat,
	} {
		var t time.Time
		if t, err = time.ParseInLocation(format, str, loc); err == nil {
			// Always return the time in the session time zone.
			return DTimestamp{Time: t.In(loc)}, nil
		}
	}

	return DummyTimestamp, err
}
Exemple #10
0
// ContainsTime tests whether a given local time is within the date range. The time range is
// from midnight on the start day to one nanosecond before midnight on the day after the end date.
// Empty date ranges (i.e. zero days) never contain anything.
//
// If a calculation needs to be 'half-open' (i.e. the end date is exclusive), simply use the
// expression 'dateRange.ExtendBy(-1).ContainsTime(t)'
func (dateRange DateRange) ContainsTime(t time.Time) bool {
	if dateRange.days == 0 {
		return false
	}
	utc := t.In(time.UTC)
	return !(utc.Before(dateRange.StartUTC()) || dateRange.EndUTC().Add(minusOneNano).Before(utc))
}
Exemple #11
0
func (engine *Engine) TZTime(t time.Time) time.Time {

	if NULL_TIME != t { // if time is not initialized it's not suitable for Time.In()
		return t.In(engine.TZLocation)
	}
	return t
}
Exemple #12
0
func TimeZoneFormat(t time.Time, tz, format string) string {
	loc, err := time.LoadLocation(tz)
	if err != nil {
		return t.Format(TimeFormat(format))
	}
	return t.In(loc).Format(TimeFormat(format))
}
Exemple #13
0
// formatTs formats t with an optional offset into a format lib/pq understands,
// appending to the provided tmp buffer and reallocating if needed. The function
// will then return the resulting buffer. formatTs is mostly cribbed from
// github.com/lib/pq.
func formatTs(t time.Time, offset *time.Location, tmp []byte) (b []byte) {
	// Need to send dates before 0001 A.D. with " BC" suffix, instead of the
	// minus sign preferred by Go.
	// Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on
	if offset != nil {
		t = t.In(offset)
	} else {
		t = t.UTC()
	}
	bc := false
	if t.Year() <= 0 {
		// flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11"
		t = t.AddDate((-t.Year())*2+1, 0, 0)
		bc = true
	}

	if offset != nil {
		b = t.AppendFormat(tmp, pgTimeStampFormat)
	} else {
		b = t.AppendFormat(tmp, pgTimeStampFormatNoOffset)
	}

	if bc {
		b = append(b, " BC"...)
	}
	return b
}
Exemple #14
0
// Constructor for MarkitChartAPIRequests
func NewMarkitChartAPIRequest(s *Stock, start time.Time, end time.Time) (*MarkitChartAPIRequest, error) {
	loc, err := time.LoadLocation("UTC")
	request := &MarkitChartAPIRequest{
		Stock:     s,
		StartDate: start.In(loc).Format(ISOFormat), // formatted like 2011-06-01T00:00:00-00 in UTC time
		EndDate:   end.In(loc).Format(ISOFormat),
		Url:       markitChartAPIURL,
	}

	// use object to build json parameters for url
	params := MarkitChartAPIRequestParams{
		Normalized: false,
		StartDate:  request.StartDate,
		EndDate:    request.EndDate,
		DataPeriod: "Day",
		Elements: []Element{
			Element{
				Symbol: s.Symbol,
				Type:   "price",
				Params: []string{"ohlc"},
			},
			Element{
				Symbol: s.Symbol,
				Type:   "volume",
			},
		},
	}
	jsonStr, err := json.Marshal(params)
	request.Url = fmt.Sprintf("%s?parameters=%s", request.Url, jsonStr)

	return request, err
}
func BuildTime(ts time.Time) string {
	loc, _ := time.LoadLocation("America/New_York")
	hour_format := "15"
	hour_s := ts.In(loc).Format(hour_format)
	hour, err := strconv.ParseInt(hour_s, 10, 64)
	if err != nil {
		log.Println(err)
		return ""
	}
	var format string
	if hour > 11 {
		format = ":04 PM, Mon Jan 2"
	} else {
		format = ":04 AM, Mon Jan 2"
	}
	var hour_in12 int
	if hour > 12 { // 1 (PM)
		hour_in12 = int(hour - 12)
	} else if hour > 0 { // 11 (AM)
		hour_in12 = int(hour)
	} else {
		hour_in12 = 12 // midnight
	}
	// final time: {hour_in12}:04 {AM/PM}, Mon Jan 2
	readable_time := strconv.Itoa(hour_in12) + ts.In(loc).Format(format)
	return readable_time
}
Exemple #16
0
// TimeToJST changes time.Time to Tokyo time zone
func TimeToJST(t time.Time) time.Time {
	jst, err := time.LoadLocation("Asia/Tokyo")
	if err != nil {
		return t
	}
	return t.In(jst)
}
Exemple #17
0
func TestTrackTrackCargo(t *testing.T) {
	var (
		cargos         = repository.NewInMemcargo()
		handlingEvents = repository.NewInMemHandlingEvent()
		service        = NewService(cargos, handlingEvents)
	)

	c := cargo.New("TEST", cargo.RouteSpecification{
		Origin:          "SESTO",
		Destination:     "FIHEL",
		ArrivalDeadline: time.Date(2005, 12, 4, 0, 0, 0, 0, time.UTC),
	})
	cargos.Store(c)

	ctx := context.Background()

	logger := log.NewLogfmtLogger(ioutil.Discard)

	h := MakeHandler(ctx, service, logger)

	req, _ := http.NewRequest("GET", "http://example.com/tracking/v1/cargos/TEST", nil)
	rec := httptest.NewRecorder()

	h.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Errorf("rec.Code = %d; want = %d", rec.Code, http.StatusOK)
	}

	if content := rec.Header().Get("Content-Type"); content != "application/json; charset=utf-8" {
		t.Errorf("Content-Type = %q; want = %q", content, "application/json; charset=utf-8")
	}

	var response trackCargoResponse
	if err := json.NewDecoder(rec.Body).Decode(&response); err != nil {
		t.Error(err)
	}

	if response.Err != nil {
		t.Errorf("response.Err = %q", response.Err)
	}

	var eta time.Time

	want := Cargo{
		TrackingID:           "TEST",
		Origin:               "SESTO",
		Destination:          "FIHEL",
		ArrivalDeadline:      time.Date(2005, 12, 4, 0, 0, 0, 0, time.UTC),
		ETA:                  eta.In(time.UTC),
		StatusText:           "Not received",
		NextExpectedActivity: "There are currently no expected activities for this cargo.",
		Events:               nil,
	}

	if !reflect.DeepEqual(want, *response.Cargo) {
		t.Errorf("response.Cargo = %#v; want = %#v", response.Cargo, want)
	}
}
func (p *bplistGenerator) writeDateTag(t time.Time) {
	tag := uint8(bpTagDate) | 0x3
	val := float64(t.In(time.UTC).UnixNano()) / float64(time.Second)
	val -= 978307200 // Adjust to Apple Epoch

	binary.Write(p.writer, binary.BigEndian, tag)
	binary.Write(p.writer, binary.BigEndian, val)
}
Exemple #19
0
// timeToPgBinary calculates the Postgres binary format for a timestamp. The timestamp
// is represented as the number of microseconds between the given time and Jan 1, 2000
// (dubbed the pgEpochJDate), stored within an int64.
func timeToPgBinary(t time.Time, offset *time.Location) int64 {
	if offset != nil {
		t = t.In(offset)
	} else {
		t = t.UTC()
	}
	return duration.DiffMicros(t, pgEpochJDate)
}
Exemple #20
0
// makeDDate constructs a DDate from a time.Time in the session time zone.
func (ctx EvalContext) makeDDate(t time.Time) (Datum, error) {
	loc, err := ctx.GetLocation()
	if err != nil {
		return DNull, err
	}
	year, month, day := t.In(loc).Date()
	return DDate{Time: time.Date(year, month, day, 0, 0, 0, 0, time.UTC)}, nil
}
Exemple #21
0
func (s *querysrv) getDeviceSeen(device protocol.DeviceID) (time.Time, error) {
	row := s.prep["selectDevice"].QueryRow(device.String())
	var seen time.Time
	if err := row.Scan(&seen); err != nil {
		return time.Time{}, err
	}
	return seen.In(time.UTC), nil
}
Exemple #22
0
func printTime(date time.Time) {
	date = date.In(time.Local)
	fmt.Println("Local: \t\t\t", date)
	fmt.Println("UTC: \t\t\t", date.UTC())
	fmt.Println("timestamp: \t\t", date.Unix())
	fmt.Println("Milli timestamp: \t", date.Unix()*1000)
	fmt.Println("Nano timestamp: \t", date.UnixNano())
}
Exemple #23
0
func (r *TimeRange) isInTimeRange(t time.Time) bool {
	t = t.In(r.loc)
	ts := NewTimeOfDay(t.Clock()).d

	if r.startTime.d > r.endTime.d {
		return !(r.endTime.d < ts && ts < r.startTime.d)
	}
	return r.startTime.d <= ts && ts <= r.endTime.d
}
Exemple #24
0
func GetLog(project string, from, to string, limit int) <-chan map[string]Log {
	output := make(chan map[string]Log)

	location, _ := time.LoadLocation("Europe/Kiev")

	cluster := gocql.NewCluster("10.1.51.65", "10.1.51.66")
	cluster.NumConns = 1
	cluster.NumStreams = 64
	cluster.MaxPreparedStmts = 2000

	cluster.Keyspace = "avp"
	session, _ := cluster.CreateSession()
	defer session.Close()
	var keyword, cat, subcat, city, item string
	var timedata time.Time

	var rank int

	//var paramsToGrab

	iter := session.Query(fmt.Sprintf("select rank, keyword, cat, subcat, city, time, item from rank_log where project = %v and time > '%v' and time < '%v' limit %v", project, from, to, limit)).Consistency(gocql.One).Iter()

	const timeform = "02 Jan 06 15:04 (MST)"

	const dayform = "2006-01-02Z01:00 (RFC3339)"

	logged = make(map[string]Log)

	response := make(map[string]Log)

	go func() {

		for iter.Scan(&rank, &keyword, &cat, &subcat, &city, &timedata, &item) {

			time := timedata

			t := timedata.In(location).Format(timeform)
			day := time.In(location).Format(dayform)

			dayTime := strings.Split(day, "Z")

			response[item] = Log{rank, keyword, cat, subcat, city, t, dayTime[0], 0, 1}

			//logged = Aggregate(logged, valLog, item);

		}

		output <- response

	}()

	if err := iter.Close(); err != nil {
		log.Fatal(err)
	}

	return output
}
Exemple #25
0
// makeDDate constructs a DDate from a time.Time in the session time zone.
func (ctx EvalContext) makeDDate(t time.Time) (DDate, error) {
	loc, err := ctx.GetLocation()
	if err != nil {
		return DDate(0), err
	}
	year, month, day := t.In(loc).Date()
	secs := time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Unix()
	return DDate(secs / secondsInDay), nil
}
Exemple #26
0
func (k Weekend) Available(t time.Time) bool {
	t = t.In(timeZone)

	// Weekend starts at 3pm Friday and ends Sunday night.
	d := t.Weekday()
	if d == time.Friday && t.Hour() >= 17 {
		return true
	}
	return d == time.Saturday || d == time.Sunday
}
Exemple #27
0
func renderDate(t time.Time) string {
	// TODO(sadovsky): For now, we always use Pacific time.
	loc, err := time.LoadLocation("America/Los_Angeles")
	CheckError(err)
	if t.Equal(time.Unix(0, 0)) {
		loc = time.UTC
	}
	// return t.In(loc).Format("Jan 2 15:04:05")
	return t.In(loc).Format("Jan 2")
}
func convertToTimezone(when time.Time, timezone string, layout string) string {
	loc, err := time.LoadLocation(timezone)
	if err != nil {
		evergreen.Logger.Errorf(slogger.WARN, "Could not load location from timezone %v: %v", timezone, err)
		return when.Format(layout)
	}

	whenTZ := when.In(loc)
	return whenTZ.Format(layout)
}
Exemple #29
0
func (tg *TimeGlob) Next(now time.Time) time.Time {
	// Find the closest time which matches the glob and is after now. Returns
	// UNKNOWN if there isn't a match.

	result := tg.nextDate(now.In(tg.location))
	if result != UNKNOWN {
		result = result.In(now.Location())
	}

	return result
}
Exemple #30
0
func (tg *TimeGlob) Prev(now time.Time) time.Time {
	// Find the closest time which matches the glob and is before, or equal to
	// now. Returns UNKNOWN if there isn't a match.

	result := tg.prevDate(now.In(tg.location))
	if result != UNKNOWN {
		result = result.In(now.Location())
	}

	return result
}