Beispiel #1
0
func convertTimeFormat(t time.Time, n byte) string {
	switch n {
	case 'a':
		return t.Weekday().String()[:3]
	case 'A':
		return t.Weekday().String()
	case 'b':
		return t.Month().String()[:3]
	case 'B':
		return t.Month().String()
	case 'c':
		return t.Format("ANSIC")
	case 'd':
		return fmt.Sprintf("%02d", t.Day())
	case 'H':
		return fmt.Sprintf("%02d", t.Hour())
	case 'I':
		hr := t.Hour() % 12
		if hr == 0 {
			hr = 12
		}
		return fmt.Sprintf("%02d", hr)
	case 'm':
		return fmt.Sprintf("%02d", t.Month())
	case 'M':
		return fmt.Sprintf("%02d", t.Minute())
	case 'p':
		if t.Hour() > 11 {
			return "PM"
		}
		return "AM"
	case 'S':
		return fmt.Sprintf("%02d", t.Second())
	case 'x':
		return t.Format("Mon Jan 02")
	case 'X':
		return t.Format("15:04:05")
	case 'y':
		year := fmt.Sprintf("%04d", t.Year())
		if l := len(year); l > 2 {
			return year[l-2 : l]
		}
		return year
	case 'Y':
		return fmt.Sprintf("%04d", t.Year())
	case 'j':
		return fmt.Sprintf("%02d", t.YearDay())
	case 'w':
		return fmt.Sprintf("%02d", t.Weekday())
	case 'U':
		_, w := t.ISOWeek()
		return fmt.Sprintf("%02d", w)
	case 'W':
		_, w := t.ISOWeek()
		return fmt.Sprintf("%02d", w)
	default:
		return string(n)
	}
}
Beispiel #2
0
// History
func (h *Hound) History() {

	eventsSlices := h.getHistoryEvents()
	events := make([]*Event, 0)
	for _, eventsSlice := range eventsSlices {
		for _, event := range eventsSlice {
			events = append(events, event)
		}
	}

	sort.Sort(ByDate{events})

	now := time.Now()
	currentDay := new(time.Time)

	re := regexp.MustCompile(" +")

	for _, event := range events {
		if event.On.YearDay() != currentDay.YearDay() {
			var dateStr string
			if event.On.YearDay() == now.YearDay() {
				dateStr = "Today"
			} else {
				dateStr = event.On.Format("Monday 02 January")
			}
			fmt.Printf(sgr.MustParseln("[bg-94 fg-184] %- 80s "), dateStr)
			currentDay = &event.On
		}

		switch T := event.Payload.(type) {
		default:
			fmt.Printf("unexpected type %T", T)

		case *gogithub.Event:
			payload := event.Payload.(*gogithub.Event)
			fmt.Printf(sgr.MustParseln(eventTemplate), event.On.Format("15:04"), event.Type, payload.Message(""))

		case *gojira.Issue:
			payload := event.Payload.(*gojira.Issue)
			fmt.Printf(sgr.MustParseln(eventTemplate), event.On.Format("15:04"), event.Type, payload.Key+" - "+payload.Fields.Summary)

		case *gojira.ActivityItem:
			payload := event.Payload.(*gojira.ActivityItem)
			fmt.Printf(sgr.MustParseln(eventTemplate), event.On.Format("15:04"), event.Type, re.ReplaceAllString(payload.Title, " "))

		case *gogitlab.Commit:
			payload := event.Payload.(*gogitlab.Commit)
			description := fmt.Sprintf(sgr.MustParse("%s - %s by [bold]%s"), payload.Short_Id, payload.Title, payload.Author_Name)
			fmt.Printf(sgr.MustParseln(eventTemplate), event.On.Format("15:04"), event.Type, description)

		case *gogitlab.FeedCommit:
			payload := event.Payload.(*gogitlab.FeedCommit)
			fmt.Printf(sgr.MustParseln(eventTemplate), event.On.Format("15:04"), event.Type, payload.Title)
		}
	}
}
Beispiel #3
0
/*
	get season scaler from time
*/
func (de *DateEncoder) getSeasonScaler(date time.Time) float64 {
	if de.seasonEncoder == nil {
		return 0.0
	}

	//make year 0 based
	dayOfYear := float64(date.YearDay() - 1)
	return dayOfYear

}
Beispiel #4
0
func same(d date.Date, t time.Time) bool {
	yd, wd := d.ISOWeek()
	yt, wt := t.ISOWeek()
	return d.Year() == t.Year() &&
		d.Month() == t.Month() &&
		d.Day() == t.Day() &&
		d.Weekday() == t.Weekday() &&
		d.YearDay() == t.YearDay() &&
		yd == yt && wd == wt
}
Beispiel #5
0
func (trs TimeRangeSchedule) adjustTime(t time.Time) {
	yearDay := t.YearDay()
	if trs.startTime.YearDay() != yearDay {
		trs.startTime = time.Date(t.Year(), t.Month(), t.Day(), trs.startTime.Hour(),
			trs.startTime.Minute(), 0, 0, time.Local)
	}
	if trs.endTime.YearDay() != yearDay {
		trs.endTime = time.Date(t.Year(), t.Month(), t.Day(), trs.endTime.Hour(),
			trs.endTime.Minute(), 0, 0, time.Local)
	}
}
Beispiel #6
0
// Strftime formats time according to the directives in the given format string. Any text not listed as a directive will be
// passed through to the output string.
//
// Format meanings:
//
//		[%a]   The abbreviated weekday name (۳ش)
//		[%A]   The full weekday name (یکشنبه)
//		[%b]   The month name (اردیبهشت)
//		[%B]   The month name in pinglish (Ordibehesht)
//		[%d]   Day of the month (01..31)
//		[%e]   Day of the month (1..31)
//		[%j]   Day of the year (1..366)
//		[%m]   Month of the year, zero-padded (01..12)
//		[%_m]  Month of the year, blank-padded ( 1..12)
//		[%-m]  Month of the year, no-padded (1..12)
//		[%w]   Day of the week (Sunday is 0, 0..6)
//		[%x]   Preferred representation for the date alone, no time in format YY/M/D
//		[%y]   Year without a century (00..99)
//		[%Y]   Year with century
//		[%H]   Hour of the day, 24-hour clock (00..23)
//		[%I]   Hour of the day, 12-hour clock (01..12)
//		[%M]   Minute of the hour (00..59)
//		[%p]   Meridian indicator ("بعد از ظهر" or "قبل از ظهر")
//		[%S]   Second of the minute (00..60)
//		[%x]   1392/04/02
//		[%-x]  92/4/2
//		[%X]   Preferred representation for the time alone, no date
//		[%Z]   Time zone name
//		[%%]   Literal %'' character
//
// Example:
// 		jalali.Strftime("Printed on %Y/%m/%d", time.Now())   #=> "Printed on 1392/04/02"
func Strftime(format string, t time.Time) string {
	jyear, jmonth, jday := Gtoj(t)
	output := format
	yy := fmt.Sprintf("%d", jyear)[2:]
	hh := t.Hour()
	if t.Hour() >= 12 {
		hh = t.Hour() - 12
	}
	ampm := persianMeridianIndicatorShort[0]
	if t.Hour() >= 12 {
		ampm = persianMeridianIndicatorShort[1]
	}
	AMPM := persianMeridianIndicator[0]
	if t.Hour() >= 12 {
		AMPM = persianMeridianIndicator[1]
	}

	zone, _ := t.Zone()

	// X:=[("%02d" % @hour),("%02d" % @min),("%02d" % @sec)].join(":"))
	re := [][]string{
		{"%%", "SUBSTITUTION_MARKER"},
		{"%m", fmt.Sprintf("%02d", jmonth)},
		{"%_m", fmt.Sprintf("% 2d", jmonth)},
		{"%-m", fmt.Sprintf("%d", jmonth)},
		{"%a", persianWeekdayNamesShort[t.Weekday()]},
		{"%A", persianWeekdayNames[t.Weekday()]},
		{"%b", persianMonthNames[jmonth]},
		{"%B", persianMonthNamesPEnglish[jmonth]},
		{"%d", fmt.Sprintf("%02d", jday)},
		{"%e", fmt.Sprintf("%d", jday)},
		{"%Y", fmt.Sprintf("%d", jyear)},
		{"%y", yy},
		{"%j", fmt.Sprintf("%d", t.YearDay())},
		{"%H", fmt.Sprintf("%02d", t.Hour())},
		{"%I", fmt.Sprintf("%02d", hh)},
		{"%M", fmt.Sprintf("%02d", t.Minute())},
		{"%S", fmt.Sprintf("%02d", t.Second())},
		{"%p", ampm},
		{"%P", AMPM},
		{"%w", fmt.Sprintf("%d", t.Weekday())},
		{"%Z", zone},
		{"%X", fmt.Sprintf("%02d:%02d:%02d", t.Hour(), t.Minute(), t.Second())},
		{"%x", fmt.Sprintf("%d/%02d/%02d", jyear, t.Month(), t.Day())},
		{"%-x", fmt.Sprintf("%s/%d/%d", yy, t.Month(), t.Day())},
		{"SUBSTITUTION_MARKER", "%"},
	}
	for _, r := range re {
		output = strings.Replace(output, r[0], r[1], -1)
	}
	return output
}
Beispiel #7
0
func daysDiff(a, b time.Time) (days int) {
	cur := b
	for cur.Year() < a.Year() {
		// add 1 to count the last day of the year too.
		days += lastDayOfYear(cur).YearDay() - cur.YearDay() + 1
		cur = firstDayOfNextYear(cur)
	}
	days += a.YearDay() - cur.YearDay()
	if b.AddDate(0, 0, days).After(a) {
		days -= 1
	}
	return days
}
Beispiel #8
0
func FuzzyTime(t time.Time) string {
	n := time.Now()
	ny, nm, nd := n.Date()
	ty, tm, td := t.Date()
	if ty == ny && tm == nm && td == nd {
		return t.Format("15:04:05")
	}
	if d := n.YearDay() - t.YearDay(); ny == ty && d > -8 && d < 8 {
		return t.Format("02 Jan 06 at 15:04")
	}

	return t.Format("Mon, 02 Jan 06 at 15:04")
}
Beispiel #9
0
func weekNumber(t *time.Time, char int) int {
	weekday := int(t.Weekday())

	if char == 'W' {
		// Monday as the first day of the week
		if weekday == 0 {
			weekday = 6
		} else {
			weekday -= 1
		}
	}

	return (t.YearDay() + 6 - weekday) / 7
}
Beispiel #10
0
// fromTime converts a time.Time value in a microsecond resolution timestamp.
func TimeMicro(t time.Time) int64 {
	// Ensure the time is in UTC
	t = t.UTC()

	yr := int64(t.Year() - 1)

	// Elapsed taking in to account leap years.
	elapsedDays := int64(yr*365+yr/4-yr/100+yr/400) + int64(t.YearDay()) - 1

	// Remaining seconds.
	elapsedSeconds := (elapsedDays*secondsPerDay + int64(t.Hour())*3600 + int64(t.Minute())*60 + int64(t.Second()))

	return int64(elapsedSeconds*microsPerSecond + int64(t.Nanosecond())/microsPerNano)
}
Beispiel #11
0
// matches determines whether the given date is the one referred to by the
// Holiday.
func (h *Holiday) matches(date time.Time) bool {
	if h.Month > 0 {
		if date.Month() != h.Month {
			return false
		}
		if h.Day > 0 {
			return date.Day() == h.Day
		}
		if h.Weekday > 0 && h.Offset != 0 {
			return IsWeekdayN(date, h.Weekday, h.Offset)
		}
	} else if h.Offset > 0 {
		return date.YearDay() == h.Offset
	}
	return false
}
Beispiel #12
0
func urlPlaceholders(t time.Time, title string, categories []string) store {
	var (
		year  = t.Year()
		month = t.Month()
		day   = t.Day()
		ph    = store{}
	)
	ph["year"] = fmt.Sprintf("%d", year)
	ph["month"] = fmt.Sprintf("%02d", month)
	ph["i_month"] = fmt.Sprintf("%d", month)
	ph["day"] = fmt.Sprintf("%02d", day)
	ph["i_day"] = fmt.Sprintf("%d", day)
	ph["short_month"] = t.Format("Jan")
	ph["y_day"] = fmt.Sprintf("%d", t.YearDay())
	ph["title"] = title
	ph["categories"] = path.Join(categories...)
	return ph
}
Beispiel #13
0
func numOfDaysBetween(from, to time.Time) (count int) {
	years := yearsBetween(from, to)
	if len(years) == 0 {
		return to.YearDay() - from.YearDay()
	}
	for _, v := range years {
		count += daysInYear(v)
	}
	currentYearDays := daysInYear(from.Year()) - from.YearDay()
	count += currentYearDays + to.YearDay()
	return
}
Beispiel #14
0
// returns decimal year to nearest 52 minutes - usually printed with %9.4f
func StarDate(when time.Time) float64 {
	yr := float64(when.Year())
	dayofyear := float64(when.YearDay())
	//fmt.Printf("%v %v\n", yr, dayofyear)
	var daysinyear float64
	if LeapYear(when) {
		daysinyear = 366
	} else {
		daysinyear = 365
	}
	// note Hour is rounded so should add fraction for Minutes*60+Seconds
	elapsedSeconds := when.Hour() * 3600
	elapsedSeconds += +when.Minute() * 60
	elapsedSeconds += when.Second()
	hrs := (dayofyear-1)*24 + (float64(elapsedSeconds) / 3600.0)
	//fmt.Printf("hrs = %v \n",hrs)
	// TODO should be rounded to .0000
	rv := yr + hrs/(daysinyear*24)
	//rv = math.Round(rv,4 places)
	return rv
}
Beispiel #15
0
func (c *ctx) initTime(config *ctxConfig, t time.Time) {
	if config.date {
		c.year, c.month, c.day = t.Date()
	}
	if config.clock {
		c.hour, c.min, c.sec = t.Clock()
	}
	if config.iso {
		c.isoYear, c.isoWeek = t.ISOWeek()
	}

	if config.millis {
		c.millis = t.Nanosecond() / 1000000
	}

	if config.yearday {
		c.yearday = t.YearDay()
	}

	if config.weekday {
		c.weekday = t.Weekday()
	}
}
Beispiel #16
0
// matches determines whether the given date is the one referred to by the
// Holiday.
func (h *Holiday) matches(date time.Time) bool {

	if h.Func != nil && (date.Year() != h.lastYear || date.Location() != h.lastLoc) {
		h.Month, h.Day = h.Func(date.Year(), date.Location())
		h.lastYear = date.Year()
		h.lastLoc = date.Location()
	}

	if h.Month > 0 {
		if date.Month() != h.Month {
			return false
		}
		if h.Day > 0 {
			return date.Day() == h.Day
		}
		if h.Weekday > 0 && h.Offset != 0 {
			return IsWeekdayN(date, h.Weekday, h.Offset)
		}
	} else if h.Offset > 0 {
		return date.YearDay() == h.Offset
	}
	return false
}
Beispiel #17
0
// scheduleLiveIDs returns a slice of all youtubeUrl field values where isLivestream == true
// for the current day or event first day if start date is in the future comparing to now.
// Keynote element is always first, even if its youtubeUrl value is empty.
func scheduleLiveIDs(c context.Context, now time.Time) ([]string, error) {
	d, err := getLatestEventData(c, nil)
	if err != nil {
		return nil, err
	}
	if d.Sessions == nil {
		return nil, nil
	}

	now = now.In(config.Schedule.Location)
	start := config.Schedule.Start.In(config.Schedule.Location)
	theday := start.YearDay()
	if now.After(start) {
		theday = now.YearDay()
	}

	live := sortedChannelSessions(make([]*eventSession, 0, len(d.Sessions)/2))
	for id, s := range d.Sessions {
		sday := s.StartTime.In(config.Schedule.Location).YearDay()
		if id == keynoteID || !s.hasLiveChannel() || sday != theday {
			continue
		}
		live = append(live, s)
	}
	sort.Sort(live)

	keyURL := ""
	if s, ok := d.Sessions[keynoteID]; ok && s.IsLive {
		keyURL = s.YouTube
	}

	res := []string{keyURL}
	for _, s := range live {
		res = append(res, s.YouTube)
	}
	return unique(res), nil
}
Beispiel #18
0
Datei: lib.go Projekt: kbj/papers
func client(id string, lib *library) {
	var clock time.Time
	var t time.Duration
	var waitTime, ioTime time.Duration
	var nRequests int
	var today int

	var resp response

	ch := make(chan response, *chanBufSize)

	today = clock.YearDay()

	for clock.YearDay() != 90 {
		if clock.YearDay() != today && id == "1" {
			log.Println(today)
		}
		today = clock.YearDay()

		nRequests++
		t = 0

		// a client requests a tape to be mounted
		//fmt.Printf("[%v client %v] mount request\n", clock.Format(timeformat), id)
		lib.changers <- request{mount, ch, clock}

		// an awaits a reference to the drive that is ready
		resp = <-ch
		clock = clock.Add(resp.t)
		//fmt.Printf("[%v client %v] tape mounted in %v\n", clock.Format(timeformat), id, resp.t)

		waitTime += resp.t

		t += resp.t

		// then sends the request
		resp.ch <- request{read, ch, clock}

		// and awaits completion
		resp = <-ch
		clock = clock.Add(resp.t)
		t += resp.t
		ioTime += resp.t
		//fmt.Printf("[%v client %v] io request finished in %v (total %v)\n",
		//	clock.Format(timeformat), id, resp.t, t)

	}

	//fmt.Printf("[%v client %v] requests: %v waittime: %v (avg: %v) ioTime: %v\n",
	//	clock.Format(timeformat), id, nRequests, waitTime, time.Duration(int(waitTime)/nRequests), ioTime)

}
Beispiel #19
0
// Strftime formats time.Date according to the directives in the given format string. The directives begins with a percent (%) character.
func Strftime(t *time.Time, f string) string {
	var result []string
	format := []rune(f)

	add := func(str string) {
		result = append(result, str)
	}

	for i := 0; i < len(format); i++ {
		switch format[i] {
		case '%':
			if i < len(format)-1 {
				switch format[i+1] {
				case 'a':
					add(shortDayNames[t.Weekday()])
				case 'A':
					add(longDayNames[t.Weekday()])
				case 'w':
					add(fmt.Sprintf("%d", t.Weekday()))
				case 'd':
					add(fmt.Sprintf("%02d", t.Day()))
				case 'b':
					add(shortMonthNames[t.Month()])
				case 'B':
					add(longMonthNames[t.Month()])
				case 'm':
					add(fmt.Sprintf("%02d", t.Month()))
				case 'y':
					add(fmt.Sprintf("%02d", t.Year()%100))
				case 'Y':
					add(fmt.Sprintf("%02d", t.Year()))
				case 'H':
					add(fmt.Sprintf("%02d", t.Hour()))
				case 'I':
					if t.Hour() == 0 {
						add(fmt.Sprintf("%02d", 12))
					} else if t.Hour() > 12 {
						add(fmt.Sprintf("%02d", t.Hour()-12))
					} else {
						add(fmt.Sprintf("%02d", t.Hour()))
					}
				case 'p':
					if t.Hour() < 12 {
						add("AM")
					} else {
						add("PM")
					}
				case 'M':
					add(fmt.Sprintf("%02d", t.Minute()))
				case 'S':
					add(fmt.Sprintf("%02d", t.Second()))
				case 'f':
					add(fmt.Sprintf("%06d", t.Nanosecond()/1000))
				case 'z':
					add(t.Format("-0700"))
				case 'Z':
					add(t.Format("MST"))
				case 'j':
					add(fmt.Sprintf("%03d", t.YearDay()))
				case 'U':
					add(fmt.Sprintf("%02d", weekNumber(t, 'U')))
				case 'W':
					add(fmt.Sprintf("%02d", weekNumber(t, 'W')))
				case 'c':
					add(t.Format("Mon Jan 2 15:04:05 2006"))
				case 'x':
					add(fmt.Sprintf("%02d/%02d/%02d", t.Month(), t.Day(), t.Year()%100))
				case 'X':
					add(fmt.Sprintf("%02d:%02d:%02d", t.Hour(), t.Minute(), t.Second()))
				case '%':
					add("%")
				}
				i += 1
			}
		default:
			add(string(format[i]))
		}
	}

	return strings.Join(result, "")
}
Beispiel #20
0
func yearDay(t time.Time) string {
	return strconv.FormatInt(int64(t.YearDay()), 36)
}
Beispiel #21
0
func dtFmtj(t time.Time, b []byte) []byte {
	j := fmt.Sprintf("%03d", t.YearDay())
	return append(b, []byte(j)...)
}
Beispiel #22
0
func datePart(part string, t time.Time) (*dparval.Value, error) {
	// now look for the requested part
	switch part {
	case "century":
		cen := float64(t.Year() / 100.0)
		if cen > 0 {
			cen = cen + 1 // there is no century 0
		}
		return dparval.NewValue(cen), nil
	case "day":
		return dparval.NewValue(float64(t.Day())), nil
	case "decade":
		return dparval.NewValue(float64(t.Year() / 10.0)), nil
	case "dow":
		return dparval.NewValue(float64(t.Weekday())), nil
	case "doy":
		return dparval.NewValue(float64(t.YearDay())), nil
	case "epoch":
		return dparval.NewValue(float64(t.Unix())), nil
	case "hour":
		return dparval.NewValue(float64(t.Hour())), nil
	case "isodow":
		isodow := float64(t.Weekday())
		if isodow == 0.0 {
			isodow = 7.0
		}
		return dparval.NewValue(isodow), nil
	case "isoyear":
		y, _ := t.ISOWeek()
		return dparval.NewValue(float64(y)), nil
	case "microseconds":
		us := float64(t.Second() * 1000000)
		us = us + float64(t.Nanosecond()/int(time.Microsecond))
		return dparval.NewValue(us), nil
	case "millennium":
		mil := float64(t.Year() / 1000.0)
		if mil > 0 {
			mil = mil + 1 // there is no millennium 0
		}
		return dparval.NewValue(mil), nil
	case "milliseconds":
		ms := float64(t.Second() * 1000)
		ms = ms + float64(t.Nanosecond()/int(time.Millisecond))
		return dparval.NewValue(ms), nil
	case "minute":
		return dparval.NewValue(float64(t.Minute())), nil
	case "month":
		return dparval.NewValue(float64(t.Month())), nil
	case "quarter":
		return dparval.NewValue(math.Ceil(float64(t.Month()) / 3.0)), nil
	case "second":
		return dparval.NewValue(float64(t.Second())), nil
	case "timezone":
		_, z := t.Zone()
		return dparval.NewValue(float64(z)), nil
	case "timezone_hour":
		_, z := t.Zone()
		zh := int64(z / (60 * 60))
		return dparval.NewValue(float64(zh)), nil
	case "timezone_minute":
		_, z := t.Zone()
		zh := int(z / (60 * 60))
		z = z - (zh * (60 * 60))
		zm := int64(z / 60)
		return dparval.NewValue(float64(zm)), nil
	case "week":
		_, w := t.ISOWeek()
		return dparval.NewValue(float64(w)), nil
	case "year":
		return dparval.NewValue(float64(t.Year())), nil
	default:
		return nil, fmt.Errorf("Unknown date part %s", part)
	}
}
func Strftime(layout string, t time.Time) string {
	// Implemented most useful of http://www.cplusplus.com/reference/ctime/strftime/
	// Skipped: %U, %W (not ISO week number) and modifiers E and O
	// How to use : fmt.Println( Strftime("%Y-%m-%d", time.Now()) )

	// Prepared data: time zone, utc offset, week based year, week number
	time_zone, utc_offset := t.Zone()
	minutes_offset := utc_offset / 60
	h := minutes_offset / 60
	m := minutes_offset % 60
	sign := "+"
	if utc_offset < 0 {
		sign = "-"
	}
	iso_offset := fmt.Sprintf("%v%v%02v", sign, h, m)

	week_based_year, week_num := t.ISOWeek()

	// Group patterns
	patterns_regexp := regexp.MustCompile("%[DxcFrRTX]{1}")
	patterns_positions := patterns_regexp.FindAllStringIndex(layout, 1000)

	var pattern string
	var newstr string
	pos := 0

	for _, p := range patterns_positions {
		newstr += layout[pos:p[0]]
		pos = p[1]

		pattern = layout[p[0]:p[1]]
		switch pattern {
		case "%D", "%x":
			newstr += "%m/%d/%y"
		case "%c":
			newstr += "%a %b %e %H:%M:%S %Y"
		case "%F":
			newstr += "%Y-%m-%d"
		case "%r":
			newstr += "%I:%M:%S %p"
		case "%R":
			newstr += "%H:%M"
		case "%T", "%X":
			newstr += "%H:%M"
		default:
			newstr += ""
		}
	}

	if len(newstr) > 0 {
		newstr += layout[pos:]
		layout = newstr
	}

	// Single patterns
	patterns_regexp = regexp.MustCompile("%[ZzCjGgyYmBbhdeVAauwHIMSpnt%]{1}")
	patterns_positions = patterns_regexp.FindAllStringIndex(layout, 1000)

	newstr = ""
	pos = 0

	for _, p := range patterns_positions {
		newstr += layout[pos:p[0]]
		pos = p[1]

		pattern = layout[p[0]:p[1]]
		switch pattern {
		case "%Z":
			// Timezone
			newstr += time_zone
		case "%z":
			// UTC offset
			newstr += iso_offset
		case "%C":
			// Century
			newstr += fmt.Sprintf("%v", int(t.Year()/100))
		case "%j":
			// Day of year
			newstr += fmt.Sprintf("%03v", t.YearDay())
		case "%G":
			// Week based year (4 digits)
			newstr += fmt.Sprintf("%04v", week_based_year)
		case "%g":
			// Week based year (last 2 digits)
			newstr += fmt.Sprintf("%04v", week_based_year)[2:4]
		case "%y":
			// Year (last 2 digits)
			newstr += fmt.Sprintf("%04v", t.Year())[2:4]
		case "%Y":
			// Year
			newstr += fmt.Sprintf("%04v", t.Year())
		case "%m":
			// Month (2 digit)
			newstr += fmt.Sprintf("%02v", int(t.Month()))
		case "%B":
			// Month full name
			newstr += t.Month().String()
		case "%b", "%h":
			// Month short name
			switch t.Month() {
			case time.June, time.July, time.September:
				newstr += t.Month().String()[:4]
			default:
				newstr += t.Month().String()[:3]
			}
		case "%d":
			// Day of month (2 digit)
			newstr += fmt.Sprintf("%02v", t.Day())
		case "%e":
			// Day of month
			newstr += fmt.Sprintf("%v", t.Day())
		case "%V":
			// ISO 8601 week number
			newstr += fmt.Sprintf("%v", week_num)
		case "%A":
			// Weekday
			newstr += t.Weekday().String()
		case "%a":
			// Weekday short name
			newstr += t.Weekday().String()[:3]
		case "%u":
			// Weekday number (1-7)
			newstr += fmt.Sprintf("%v", int(t.Weekday()))
		case "%w":
			// Weekday numder (0-6)
			newstr += fmt.Sprintf("%v", int(t.Weekday())-1)
		case "%H":
			// Hour (00-24)
			newstr += fmt.Sprintf("%02v", t.Hour())
		case "%I":
			// Hour (00-12)
			newstr += fmt.Sprintf("%02v", t.Hour()-(t.Hour()/12)*12)
		case "%M":
			// Minute (00-59)
			newstr += fmt.Sprintf("%02v", t.Minute())
		case "%S":
			// Second (00-59)
			newstr += fmt.Sprintf("%02v", t.Second())
		case "%p":
			// AM/PM
			if t.Hour()/12 > 0 {
				newstr += "PM"
			} else {
				newstr += "AM"
			}
		case "%n":
			newstr += "\n"
		case "%t":
			newstr += "\t"
		case "%%":
			newstr += "%"
		default:
			newstr += ""
		}
	}

	if len(newstr) > 0 {
		newstr += layout[pos:]
		layout = newstr
	}

	return layout
}
Beispiel #24
0
			parsedTime = time.Now()
		} else {
			parsedTime = time.Unix(int64(intTime), 0)
		}

		// Process time in UTC
		if formatString[0] == '!' {
			// Delete the ! character
			formatString = formatString[1:len(formatString)]
			parsedTime = parsedTime.UTC()
		}

		year, month, day := parsedTime.Date()
		hour, min, sec := parsedTime.Clock()
		wday := int(parsedTime.Weekday())
		yday := parsedTime.YearDay()

		if formatString == "*t" {
			l.CreateTable(8, 0)

			l.PushInteger(sec)
			l.SetField(-2, "sec")

			l.PushInteger(min)
			l.SetField(-2, "min")

			l.PushInteger(hour)
			l.SetField(-2, "hour")

			l.PushInteger(day)
			l.SetField(-2, "day")
Beispiel #25
0
func strftime(b *bytes.Buffer, c rune, t time.Time) error {
	switch c {
	case 'A':
		b.WriteString(t.Weekday().String())
	case 'a':
		b.WriteString(t.Weekday().String()[:3])
	case 'B':
		b.WriteString(t.Month().String())
	case 'b':
		b.WriteString(t.Month().String()[:3])
	case 'C':
		fmt.Fprintf(b, "%02d", t.Year())
	case 'D':
		y, m, d := t.Date()
		fmt.Fprintf(b, "%02d/%02d/%02d", m, d, y%100)
	case 'd':
		fmt.Fprintf(b, "%02d", t.Day())
	case 'e':
		fmt.Fprintf(b, "%2d", t.Day())
	case 'F':
		y, m, d := t.Date()
		fmt.Fprintf(b, "%04d-%02d-%02d", y, m, d)
	case 'H':
		fmt.Fprintf(b, "%02d", t.Hour())
	case 'h':
		b.WriteString(t.Month().String()[:3])
	case 'I':
		hr := t.Hour() % 12
		if hr == 0 {
			hr = 12
		}
		fmt.Fprintf(b, "%02d", hr)
	case 'j':
		fmt.Fprintf(b, "%03d", t.YearDay())
	case 'k':
		fmt.Fprintf(b, "%2d", t.Hour())
	case 'l':
		hr := t.Hour() % 12
		if hr == 0 {
			hr = 12
		}
		fmt.Fprintf(b, "%2d", hr)
	case 'M':
		fmt.Fprintf(b, "%02d", t.Minute())
	case 'm':
		fmt.Fprintf(b, "%02d", t.Month())
	case 'n':
		b.WriteByte('\n')
	case 'P':
		if t.Hour() < 12 {
			b.WriteString("am")
		} else {
			b.WriteString("pm")
		}
	case 'p':
		if t.Hour() < 12 {
			b.WriteString("AM")
		} else {
			b.WriteString("PM")
		}
	case 'R':
		h, m, _ := t.Clock()
		fmt.Fprintf(b, "%02d:%02d", h, m)
	case 'r':
		h, m, s := t.Clock()

		var tm string
		if h < 12 {
			tm = "AM"
		} else {
			tm = "PM"
		}

		hr := h % 12
		if hr == 0 {
			hr = 12
		}

		fmt.Fprintf(b, "%02d:%02d:%02d %s", hr, m, s, tm)
	case 'S':
		fmt.Fprintf(b, "%02d", t.Second())
	case 's':
		b.WriteString(strconv.FormatInt(t.Unix(), 10))
	case 'T':
		h, m, s := t.Clock()
		fmt.Fprintf(b, "%02d:%02d:%02d", h, m, s)
	case 't':
		b.WriteByte('\t')
	case 'v':
		fmt.Fprintf(b, "%2d-%s-%04d", t.Day(), t.Month().String()[:3], t.Year())
	case 'w':
		fmt.Fprintf(b, "%d", t.Weekday())
	case 'Y':
		fmt.Fprintf(b, "%04d", t.Year())
	case 'y':
		fmt.Fprintf(b, "%02d", t.Year()%100)
	case 'Z':
		zone, _ := t.Zone()
		b.WriteString(zone)
	case 'z':
		_, offset := t.Zone()
		allMinutes := int(offset / 60)
		fmt.Fprintf(b, "%+03d%02d", int(allMinutes/60), int(allMinutes%60))
	default:
		return fmt.Errorf("No valid replacement")
	}

	return nil
}
Beispiel #26
0
// is date1's date after date2's date
func isDateAfter(date1 time.Time, date2 time.Time) bool {
	return (date1.Year() == date2.Year() && date2.YearDay() < date1.YearDay()) || date2.Year() < date1.Year()
}
Beispiel #27
0
// StrftimePure is a locale-unaware implementation of strftime(3). It does not
// correctly account for locale-specific conversion specifications, so formats
// like `%c` may behave differently from the underlying platform. Additionally,
// the `%E` and `%O` modifiers are passed through as raw strings.
//
// The implementation of locale-specific conversions attempts to mirror the
// strftime(3) implementation in glibc 2.15 under LC_TIME=C.
func StrftimePure(format string, t time.Time) string {
	buf := make([]byte, 0, 512)
	for i := 0; i < len(format); {
		c := format[i]
		if c != '%' {
			buf = append(buf, c)
			i++
			continue
		}
		i++
		if i == len(format) {
			buf = append(buf, '%')
			break
		}
		b := format[i]

		switch b {
		default:
			buf = append(buf, '%', b)
		case 'a':
			// The abbreviated weekday name according to the current locale.
			buf = append(buf, t.Format("Mon")...)
		case 'A':
			// The full weekday name according to the current locale.
			buf = append(buf, t.Format("Monday")...)
		case 'b':
			// The abbreviated month name according to the current locale.
			buf = append(buf, t.Format("Jan")...)
		case 'B':
			// The full month name according to the current locale.
			buf = append(buf, t.Month().String()...)
		case 'C':
			// The century number (year/100) as a 2-digit integer. (SU)
			buf = zero2d(buf, int(t.Year())/100)
		case 'c':
			// The preferred date and time representation for the current locale.
			buf = append(buf, t.Format("Mon Jan  2 15:04:05 2006")...)
		case 'd':
			// The day of the month as a decimal number (range 01 to 31).
			buf = zero2d(buf, t.Day())
		case 'D':
			// Equivalent to %m/%d/%y. (Yecch—for Americans only. Americans should note that in other countries %d/%m/%y is rather com‐ mon. This means that in international context this format is ambiguous and should not be used.) (SU)
			buf = zero2d(buf, int(t.Month()))
			buf = append(buf, '/')
			buf = zero2d(buf, t.Day())
			buf = append(buf, '/')
			buf = zero2d(buf, t.Year()%100)
		case 'E':
			// Modifier: use alternative format, see below. (SU)
			if i+1 < len(format) {
				i++
				buf = append(buf, '%', 'E', format[i])

			} else {
				buf = append(buf, "%E"...)
			}
		case 'e':
			// Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space. (SU)
			buf = twoD(buf, t.Day())
		case 'F':
			// Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
			buf = zero4d(buf, t.Year())
			buf = append(buf, '-')
			buf = zero2d(buf, int(t.Month()))
			buf = append(buf, '-')
			buf = zero2d(buf, t.Day())
		case 'G':
			// The ISO 8601 week-based year (see NOTES) with century as a decimal number. The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead. (TZ)
			year, _ := t.ISOWeek()
			buf = zero4d(buf, year)
		case 'g':
			// Like %G, but without century, that is, with a 2-digit year (00-99). (TZ)
			year, _ := t.ISOWeek()
			buf = zero2d(buf, year%100)
		case 'h':
			// Equivalent to %b. (SU)
			buf = append(buf, t.Format("Jan")...)
		case 'H':
			// The hour as a decimal number using a 24-hour clock (range 00 to 23).
			buf = zero2d(buf, t.Hour())
		case 'I':
			// The hour as a decimal number using a 12-hour clock (range 01 to 12).
			buf = zero2d(buf, t.Hour()%12)
		case 'j':
			// The day of the year as a decimal number (range 001 to 366).
			buf = zero3d(buf, t.YearDay())
		case 'k':
			// The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (See also %H.) (TZ)
			buf = twoD(buf, t.Hour())
		case 'l':
			// The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. (See also %I.) (TZ)
			buf = twoD(buf, t.Hour()%12)
		case 'm':
			// The month as a decimal number (range 01 to 12).
			buf = zero2d(buf, int(t.Month()))
		case 'M':
			// The minute as a decimal number (range 00 to 59).
			buf = zero2d(buf, t.Minute())
		case 'n':
			// A newline character. (SU)
			buf = append(buf, '\n')
		case 'O':
			// Modifier: use alternative format, see below. (SU)
			if i+1 < len(format) {
				i++
				buf = append(buf, '%', 'O', format[i])
			} else {
				buf = append(buf, "%O"...)
			}
		case 'p':
			// Either "AM" or "PM" according to the given time value, or the corresponding strings for the current locale. Noon is treated as "PM" and midnight as "AM".
			buf = appendAMPM(buf, t.Hour())
		case 'P':
			// Like %p but in lowercase: "am" or "pm" or a corresponding string for the current locale. (GNU)
			buf = appendampm(buf, t.Hour())
		case 'r':
			// The time in a.m. or p.m. notation. In the POSIX locale this is equivalent to %I:%M:%S %p. (SU)
			h := t.Hour()
			buf = zero2d(buf, h%12)
			buf = append(buf, ':')
			buf = zero2d(buf, t.Minute())
			buf = append(buf, ':')
			buf = zero2d(buf, t.Second())
			buf = append(buf, ' ')
			buf = appendAMPM(buf, h)
		case 'R':
			// The time in 24-hour notation (%H:%M). (SU) For a version including the seconds, see %T below.
			buf = zero2d(buf, t.Hour())
			buf = append(buf, ':')
			buf = zero2d(buf, t.Minute())
		case 's':
			// The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ)
			buf = strconv.AppendInt(buf, t.Unix(), 10)
		case 'S':
			// The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.)
			buf = zero2d(buf, t.Second())
		case 't':
			// A tab character. (SU)
			buf = append(buf, '\t')
		case 'T':
			// The time in 24-hour notation (%H:%M:%S). (SU)
			buf = zero2d(buf, t.Hour())
			buf = append(buf, ':')
			buf = zero2d(buf, t.Minute())
			buf = append(buf, ':')
			buf = zero2d(buf, t.Second())
		case 'u':
			// The day of the week as a decimal, range 1 to 7, Monday being 1. See also %w. (SU)
			day := byte(t.Weekday())
			if day == 0 {
				day = 7
			}
			buf = append(buf, '0'+day)
		case 'U':
			// The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W.
			buf = zero2d(buf, (t.YearDay()-int(t.Weekday())+7)/7)
		case 'V':
			// The ISO 8601 week number (see NOTES) of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the new year. See also %U and %W. (SU)
			_, week := t.ISOWeek()
			buf = zero2d(buf, week)
		case 'w':
			// The day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u.
			buf = strconv.AppendInt(buf, int64(t.Weekday()), 10)
		case 'W':
			// The week number of the current year as a decimal number, range 00 to 53, starting with the first Monday as the first day of week 01.
			buf = zero2d(buf, (t.YearDay()-(int(t.Weekday())-1+7)%7+7)/7)
		case 'x':
			// The preferred date representation for the current locale without the time.
			buf = zero2d(buf, int(t.Month()))
			buf = append(buf, '/')
			buf = zero2d(buf, t.Day())
			buf = append(buf, '/')
			buf = zero2d(buf, t.Year()%100)
		case 'X':
			// The preferred time representation for the current locale without the date.
			buf = zero2d(buf, t.Hour())
			buf = append(buf, ':')
			buf = zero2d(buf, t.Minute())
			buf = append(buf, ':')
			buf = zero2d(buf, t.Second())
		case 'y':
			// The year as a decimal number without a century (range 00 to 99).
			buf = zero2d(buf, t.Year()%100)
		case 'Y':
			// The year as a decimal number including the century.
			buf = zero4d(buf, t.Year())
		case 'z':
			// The +hhmm or -hhmm numeric timezone (that is, the hour and minute offset from UTC). (SU)
			buf = append(buf, t.Format("-0700")...)
		case 'Z':
			// The timezone or name or abbreviation.
			buf = append(buf, t.Format("MST")...)
		case '+':
			// The date and time in date(1) format. (TZ) (Not supported in glibc2.)
			buf = append(buf, t.Format("Mon Jan _2 15:04:05 MST 2006")...)
		case '%':
			// A literal '%' character.
			buf = append(buf, '%')
		}
		i++
	}
	return string(buf)
}
Beispiel #28
0
// Strftime formats t to the directives in the given format string
// format is compatiable with ruby's Time#strftime
// see http://ruby-doc.org/core-2.2.2/Time.html#method-i-strftime
func Strftime(t *time.Time, format string) string {
	var tFormat []string

	app := func(f string, idx *int, step int) {
		tFormat = append(tFormat, f)
		*idx += step
	}

	b := []rune(format)
	for i := 0; i < len(b); i++ {
		if b[i] == '%' {
			switch b[i+1] {
			case '%': // litteral %
				app("%", &i, 1)
				continue
			case 'Y', 'G': // year
				app(t.Format("2006"), &i, 1)
				continue
			case 'C':
				s, _ := strconv.Atoi(t.Format("2006"))
				app(strconv.Itoa(s/100), &i, 1)
				continue
			case 'y', 'g':
				app(t.Format("06"), &i, 1)
				continue
			case 'm': // month
				app(t.Format("01"), &i, 1)
				continue
			case '_': // processing underlined with _m
				if b[i+2] == 'm' {
					app(fmt.Sprintf("%2s", t.Format("1")), &i, 2)
					continue
				}
			case '-': // process - with -m, -d
				if b[i+2] == 'm' {
					app(t.Format("1"), &i, 2)
					continue
				} else if b[i+2] == 'd' {
					app(t.Format("2"), &i, 2)
					continue
				}
			case 'B':
				app(t.Format("January"), &i, 1)
				continue
			case 'b', 'h':
				app(t.Format("Jan"), &i, 1)
				continue
			case '^':
				if b[i+2] == 'B' {
					app(strings.ToUpper(t.Format("January")), &i, 2)
					continue
				} else if b[i+2] == 'b' {
					app(strings.ToUpper(t.Format("Jan")), &i, 2)
					continue
				} else if b[i+2] == 'A' {
					app(strings.ToUpper(t.Weekday().String()), &i, 2)
					continue
				} else if b[i+2] == 'a' {
					app(strings.ToUpper(t.Weekday().String()[:3]), &i, 2)
					continue
				}
			case 'd':
				app(t.Format("02"), &i, 1)
				continue
			case 'e':
				app(fmt.Sprintf("%2s", t.Format("2")), &i, 1)
				continue
			case 'j':
				app(strconv.Itoa(t.YearDay()), &i, 1)
				continue
			case 'H':
				app(t.Format("15"), &i, 1)
				continue
			case 'k':
				hk, _ := strconv.Atoi(t.Format("15"))
				app(fmt.Sprintf("%2s", strconv.Itoa(hk)), &i, 1)
				continue
			case 'I':
				hki, _ := strconv.Atoi(t.Format("3"))
				app(fmt.Sprintf("%02s", strconv.Itoa(hki)), &i, 1)
				continue
			case 'l':
				hki, _ := strconv.Atoi(t.Format("3"))
				app(fmt.Sprintf("%2s", strconv.Itoa(hki)), &i, 1)
				continue
			case 'P':
				app(t.Format("am"), &i, 1)
				continue
			case 'p':
				app(t.Format("AM"), &i, 1)
				continue
			case 'M':
				app(t.Format("04"), &i, 1)
				continue
			case 'S':
				app(t.Format("05"), &i, 1)
				continue
			case 'L':
				app(t.Format(".999"), &i, 1)
				continue
			case '1', '2', '3', '4', '5', '6', '7', '8', '9':
				if b[i+2] == 'N' {
					if l, err := strconv.Atoi(string(b[i+1])); err == nil {
						app(t.Format(fslen(l)), &i, 2)
					}
				}
				continue
			case 'z':
				app(t.Format("-0700"), &i, 1)
				continue
			case 'Z':
				app(t.Format("MST"), &i, 1)
				continue
			case 'A':
				app(t.Weekday().String(), &i, 1)
				continue
			case 'a':
				app(t.Weekday().String()[:3], &i, 1)
				continue
			case 'w', 'u': // w sunday is 0,0..6 u monday is 1,1..7
				wd := int(t.Weekday() - time.Sunday)
				if wd == 0 && b[i] == 'u' {
					app(strconv.Itoa(7), &i, 1)
				} else {
					app(strconv.Itoa(wd), &i, 1)
				}
				continue
			case 'V', 'U': // todo(js): V is ISO8601. U is technically 0-based.
				_, w := t.ISOWeek()
				app(fmt.Sprintf("%02s", strconv.Itoa(w)), &i, 1)
				continue
			case 's':
				app(strconv.FormatInt(t.Unix(), 10), &i, 1)
				continue
			case 'Q':
				app(strconv.FormatInt(t.UnixNano()/1000000, 10), &i, 1)
				continue
			case 'n':
				app("\n", &i, 1)
				continue
			case 't':
				app("\t", &i, 1)
				continue
			// Combinations
			case 'c': // %c - date and time (%a %b %e %T %Y)
				app(fmt.Sprintf(
					"%s %s %s %s:%s:%s %s",
					t.Weekday().String()[:3],
					t.Format("Jan"),
					fmt.Sprintf("%2s", t.Format("2")),
					t.Format("15"),
					t.Format("04"),
					t.Format("05"),
					t.Format("2006")),
					&i, 1)
				continue
			case 'D', 'x':
				app(fmt.Sprintf("%s/%s/%s", t.Format("01"), t.Format("02"), t.Format("06")), &i, 1)
				continue
			case 'F': // %Y-%m-%d
				app(fmt.Sprintf("%s-%s-%s", t.Format("2006"), t.Format("01"), t.Format("02")), &i, 1)
				continue
			case 'v': // %e-%b-%y
				app(fmt.Sprintf("%s-%s-%s", fmt.Sprintf("%2s", t.Format("2")), t.Format("Jan"), t.Format("06")), &i, 1)
				continue
			case 'X', 'T':
				app(fmt.Sprintf("%s:%s:%s", t.Format("15"), t.Format("04"), t.Format("05")), &i, 1)
				continue
			case 'r': // %r - 12-hour time (%I:%M:%S %p)
				hki, _ := strconv.Atoi(t.Format("3"))
				app(fmt.Sprintf("%02s:%s:%s %s",
					strconv.Itoa(hki),
					t.Format("04"),
					t.Format("05"),
					t.Format("AM")),
					&i, 1)
				continue
			case 'R':
				app(fmt.Sprintf("%s:%s", t.Format("15"), t.Format("04")), &i, 1)
				continue
			}
		}
		tFormat = append(tFormat, string(b[i]))
	}
	return strings.Join(tFormat, "")
}
Beispiel #29
0
func getDateMessage(date time.Time) string {
	return fmt.Sprintf("Day %d: %s", date.YearDay(), date.Format(DateLayout))
}
Beispiel #30
0
func seedFormat(t time.Time) string {
	if time.Now().After(t) {
		return fmt.Sprintf("%04d,%03d,%s", t.Year(), t.YearDay(), t.Format("15:04:05.0000"))
	}
	return ""
}