Exemple #1
0
func newTime(now time.Time) *Time {
	year, _month, day := now.Date()
	month := int(_month)
	_, week := now.ISOWeek()
	hour := now.Hour()
	return &Time{year, month, day, hour, week}
}
Exemple #2
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)
	}
}
Exemple #3
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
}
Exemple #4
0
func PeriodHeadline(from, to time.Time, period datetime.Period) string {
	switch period {
	case datetime.Day:
		return fmt.Sprintf("%s", from.Format("2006-01-02: Monday"))
	case datetime.Week:
		_, isoWeek := from.ISOWeek()
		return fmt.Sprintf("Week %d: %s - %s", isoWeek, from.Format("2006-01-02"), to.Format("2006-01-02"))
	case datetime.Month:
		return fmt.Sprintf("%s", from.Format("January 2006"))
	case datetime.Year:
		return fmt.Sprintf("%s", from.Format("Year 2006"))
	default:
		panic("not implemeneted")
	}
}
Exemple #5
0
func NewDateFromTime(time time.Time) Date {
	date := Date{}
	date.Date = time.Format("2006-01-02")
	date.Weekend = isWeekend(time)
	date.Day = time.Weekday().String()
	_, date.WeekNumber = time.ISOWeek()
	return date
}
Exemple #6
0
func indexName(project *engine.ConfProject, indexPattern string,
	date time.Time) (index string) {
	const (
		YM  = "@ym"
		YMW = "@ymw"
		YMD = "@ymd"

		INDEX_PREFIX = "fun_"
	)

	if strings.Contains(indexPattern, YM) {
		prefix := project.IndexPrefix
		fields := strings.SplitN(indexPattern, YM, 2)
		if fields[0] != "" {
			// e,g. rs@ym
			prefix = fields[0]
		}

		switch indexPattern {
		case YM:
			index = fmt.Sprintf("%s%s_%d_%02d", INDEX_PREFIX, prefix,
				date.Year(), int(date.Month()))
		case YMW:
			year, week := date.ISOWeek()
			index = fmt.Sprintf("%s%s_%d_w%02d", INDEX_PREFIX, prefix,
				year, week)
		case YMD:
			index = fmt.Sprintf("%s%s_%d_%02d_%02d", INDEX_PREFIX, prefix,
				date.Year(), int(date.Month()), date.Day())
		}

		return
	}

	index = INDEX_PREFIX + indexPattern

	return
}
Exemple #7
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()
	}
}
Exemple #8
0
func PeriodTypeByWeek(week int64) int64 {
	t := time.Now().UTC()
	var t2 time.Time

	current_year := t.Year()
	fmt.Println(current_year)
	current_month := int(t.Month())
	_, start_week := t.ISOWeek()
	if current_month >= 9 {
		t2, _ = time.Parse("1.2.2006", fmt.Sprintf("%d.%d.%d", 9, 1, current_year))
	} else {
		t2, _ = time.Parse("1.2.2006", fmt.Sprintf("%d.%d.%d", 9, 1, current_year-1))
	}
	t2 = t2.UTC()
	_, start_week = t2.ISOWeek()
	var pt int64
	pt = 1
	if start_week%2 != 0 && week%2 == 0 {
		pt = 2
	} else if start_week%2 == 0 && week%2 != 0 {
		pt = 2
	}
	return pt
}
Exemple #9
0
func (w Week) RoundDown(t time.Time) time.Time {
	org := t.Format("Mon 2006-01-02")
	_, week := t.ISOWeek()
	shift := int64(60 * 60 * 24 * (t.Weekday() - time.Monday))
	t = t.Add(-time.Duration(shift) * time.Second)
	t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, t.Location())
	// daylight saving and that like might lead to different real shift

	_, week2 := t.ISOWeek()
	for week2 < week {
		trace.Printf("B  %s", t)
		t = t.Add(time.Second * 60 * 60 * 36)
		t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, t.Location())
		_, week2 = t.ISOWeek()
	}
	for week2 > week {
		trace.Printf("C  %s", t)
		t = t.Add(-time.Second * 60 * 60 * 36)
		t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, t.Location())
		_, week2 = t.ISOWeek()
	}
	trace.Printf("Week.Roundown(%s) --> %s", org, t.Format("Mon 2006-01-02"))
	return t
}
Exemple #10
0
// yw returns an integer in the form YYYYWW, where WW is the week number.
func yw(d time.Time) int {
	year, week := d.ISOWeek()
	return year*100 + week
}
Exemple #11
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)
	}
}
Exemple #12
0
func timetuple(t time.Time) [5]int {
	year, month, day := t.Date()
	_, week := t.ISOWeek()
	return [5]int{year, int(month), day, t.Hour(), week}
}
Exemple #13
0
func (w Week) Format(t time.Time) string {
	_, week := t.ISOWeek()
	return fmt.Sprintf("W %d", week)
}
func isSameWeek(date1 time.Time, date2 time.Time) bool {
	y1, w1 := date1.ISOWeek()
	y2, w2 := date2.ISOWeek()
	return y1 == y2 && w1 == w2
}
Exemple #15
0
// cmdCreateMilestone creates a new milestone in all projects
func cmdCreateMilestone(opts *Options, target, due, title string) error {
	tc := AuthClient(opts)
	client := github.NewClient(tc)
	config, err := LoadConfig(opts)
	if err != nil {
		return err
	}

	var date time.Time
	if due != "" {
		date, err = time.Parse("2006-01-02", due)
		if err != nil {
			return err
		}
	} else {
		// Default to Monday next week with a little wiggle room
		check := time.Now().Add(5 * 24 * time.Hour)
		check = check.Round(1 * 24 * time.Hour)
		check = check.Add(1 * time.Second)
		for check.Weekday() != 0 {
			check = check.Add(1 * 24 * time.Hour)
		}
		date = check
	}

	if title == "" {
		year, week := date.ISOWeek()
		seed, err := strconv.Atoi(fmt.Sprintf("%d%02d", year, week))
		if err != nil {
			return err
		}
		rand.Seed(int64(seed))
		ship := Titles[rand.Intn(len(Titles))]
		title = fmt.Sprintf("%d-%02d %s", year, week, ship)
	}

	var projects []string
	if target == "all" {
		projects = config.Projects
	} else {
		projects = strings.Split(target, " ")
	}

	for _, project := range projects {
		logger.Debugln("Creating milestone for:", project)

		owner, repo, err := ownerRepo(project)
		if err != nil {
			return err
		}

		// if we got here we didn't match, create a milestone
		logger.Debugf("  creating: %s (%v)", title, due)
		_, _, err = client.Issues.CreateMilestone(owner, repo, &github.Milestone{Title: &title, DueOn: &date})
		if err != nil {
			return err
		}
	}
	fmt.Printf("New Milestone: %s\n", title)
	return nil
}
Exemple #16
0
// A strftime() implementation close to POSIX; locales and modifiers (E, O,
// field width, plus, minus) are not supported, but gracefully ignored. All
// conversion specifiers should otherwise work as specified in POSIX.
func Strftime(format string, t time.Time) string {
	//fmt.Println("Strftime(", format, t, ")")
	var rbuf bytes.Buffer // result buffer
	inSpec := false       // in a specifier after reading '%'
	for _, r := range format {
		if !inSpec {
			if r == '%' {
				inSpec = true
			} else {
				rbuf.WriteRune(r)
			}
			continue
		}
		inSpec = false // true for most characters, at least
		var s string
		switch r {
		case 'E', 'O', '+', '-', '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9': // modifiers, ignored
			inSpec = true // still in a specifier
		case 'a': // locale's abbreviated weekday name
			s = t.Weekday().String()[:3]
		case 'A': // locale's full weekday name
			s = t.Weekday().String()
		case 'b', 'h': // locale's abbreviated month name
			s = t.Month().String()[:3]
		case 'B': // locale's full month name
			s = t.Month().String()
		case 'c': // locale's appropriate date and time representation
			s = Strftime(StandardFormat, t)
		case 'C':
			// Replaced by the year divided by 100 and truncated to
			// an integer, as a decimal number
			s = fmt.Sprintf("%02d", t.Year()/100)
		case 'd': // day of the month as a decimal number [01,31]
			s = fmt.Sprintf("%02d", t.Day())
		case 'D': // Equivalent to %m / %d / %y
			s = Strftime("%m/%d/%y", t)
		case 'e':
			// day of the month as a decimal number [1,31]; a
			// single digit is preceded by a space
			s = fmt.Sprintf("%2d", t.Month())
		case 'f': // Microsecond as a decimal number [000000,999999]
			s = fmt.Sprintf("%06d", t.Nanosecond()/1000)
		case 'F':
			// Equivalent to %+4Y-%m-%d if no flag and no minimum
			// field width are specified (sez POSIX)
			s = Strftime("%Y-%m-%d", t)
		case 'g':
			// last 2 digits of the week-based year as a decimal
			// number [00,99]
			year, _ := t.ISOWeek()
			s = fmt.Sprintf("%02d", year%100)
		case 'G':
			// week-based year as a decimal number (for example,
			// 1977)
			year, _ := t.ISOWeek()
			s = fmt.Sprintf("%02d", year)
		// for 'h' see 'b'
		case 'H': // hour (24-hour clock) as a decimal number [00,23]
			s = fmt.Sprintf("%02d", t.Hour())
		case 'I': // hour (12-hour clock) as a decimal number [01,12]
			hour := t.Hour() % 12
			if hour == 0 {
				hour = 12
			}
			s = fmt.Sprintf("%02d", hour)
		case 'j': // day of the year as a decimal number [001,366]
			s = fmt.Sprintf("%03d", dayOfYear(t)+1)
		case 'm': // month as a decimal number [01,12]
			s = fmt.Sprintf("%02d", int(t.Month()))
		case 'M': // minute as a decimal number [00,59]
			s = fmt.Sprintf("%02d", t.Minute())
		case 'n': // a <newline>
			s = "\n"
		case 'p': // locale's equivalent of either AM or PM.
			if t.Hour() < 12 {
				s = "AM"
			} else {
				s = "PM"
			}
		case 'r': // the time in a.m. and p.m. notation
			s = Strftime("%I:%M:%S %p", t)
		case 'R': // time in 24-hour notation
			s = fmt.Sprintf("%02d:%02d", t.Hour(), t.Minute())
		case 'S': // Second as a decimal number [00,61].
			s = fmt.Sprintf("%02d", t.Second())
		case 't': // a <tab>
			s = "\t"
		case 'T': // the time ( %H : %M : %S )
			s = fmt.Sprintf("%02d:%02d:%02d",
				t.Hour(), t.Minute(), t.Second())
		case 'u':
			// the weekday as a decimal number [1,7], with 1
			// representing Monday
			day := t.Weekday()
			if day == 0 {
				day = 7
			}
			s = fmt.Sprintf("%d", day)
		case 'U':
			// week number of the year as a decimal number [00,53].
			// The first Sunday of January is the first day of week
			// 1; days in the new year before this are in week 0
			s = weekNumber(t, time.Sunday)
		case 'v': // (BSD extension? was in OS X)
			s = Strftime("%e-%b-%Y", t)
		case 'V':
			// (ISO week number) week number of the year (Monday as
			// the first day of the week) as a decimal number
			// [01,53]. If the week containing 1 January has four
			// or more days in the new year, then it is considered
			// week 1. Otherwise, it is the last week of the
			// previous year, and the next week is week 1. Both
			// January 4th and the first Thursday of January are
			// always in week 1
			_, week := t.ISOWeek()
			s = fmt.Sprintf("%d", week)
		case 'w':
			// weekday as a decimal number [0,6], with 0
			// representing Sunday
			s = fmt.Sprintf("%d", t.Weekday())
		case 'W':
			// week number of the year as a decimal number [00,53].
			// The first Monday of January is the first day of week
			// 1; days in the new year before this are in week 0
			s = weekNumber(t, time.Monday)
		case 'x': // locale's appropriate date representation.
			s = Strftime("%Y-%m-%d", t)
		case 'X': // locale's appropriate time representation.
			s = Strftime("%H:%M:%S", t)
		case 'y':
			// last two digits of the year as a decimal number
			// [00,99]
			s = fmt.Sprintf("%02d", t.Year()%100)
		case 'Y': // year as a decimal number (for example, 1997)
			s = fmt.Sprintf("%04d", t.Year())
		case 'z':
			// offset from UTC in the ISO 8601:2000 standard format
			// ( +hhmm or -hhmm ), or by no characters if no
			// timezone is determinable. For example, "-0430" means
			// 4 hours 30 minutes behind UTC (west of Greenwich).
			// [CX] If tm_isdst is zero, the standard time offset
			// is used. If tm_isdst is greater than zero, the
			// daylight savings time offset is used. If tm_isdst is
			// negative, no characters are returned
			_, offset := t.Zone()
			min := offset / 60 % 60
			hour := offset / 3600
			s = fmt.Sprintf("%+03d%02d", hour, min)
		case 'Z':
			// timezone name or abbreviation, or by no bytes if no
			// timezone information exists
			name, _ := t.Zone()
			s = name
		case '%': // A literal '%' character.
			s = "%"
		default:
			s = fmt.Sprintf("%%!<Strftime:'%c'invalid>", r)
		}
		rbuf.WriteString(s)
	}
	//fmt.Println(rbuf)
	return rbuf.String()
}
Exemple #17
0
// Get the week number, from 1 to 53
func WeekNum(date time.Time) int {
	_, weeknum := date.ISOWeek()
	return weeknum
}
Exemple #18
0
func dtFmtg(t time.Time, b []byte) []byte {
	y, _ := t.ISOWeek()
	szy := fmt.Sprintf("%d", y)
	g := []byte{szy[2], szy[3]}
	return append(b, g...)
}
Exemple #19
0
func dtFmtG(t time.Time, b []byte) []byte {
	y, _ := t.ISOWeek()
	G := fmt.Sprintf("%d", y)
	return append(b, []byte(G)...)
}
Exemple #20
0
func dtFmtV(t time.Time, b []byte) []byte {
	_, w := t.ISOWeek()
	V := fmt.Sprintf("%02d", w)
	return append(b, []byte(V)...)
}
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
}
Exemple #22
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)
}
Exemple #23
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, "")
}
Exemple #24
0
func replaceDateTag(d time.Time, input, output *bytes.Buffer) {
	r, _, err := input.ReadRune()

	if err != nil {
		return
	}

	switch r {
	case '%':
		output.WriteString("%")
	case 'a':
		output.WriteString(getShortWeekday(d.Weekday()))
	case 'A':
		output.WriteString(getLongWeekday(d.Weekday()))
	case 'b', 'h':
		output.WriteString(getShortMonth(d.Month()))
	case 'B':
		output.WriteString(getLongMonth(d.Month()))
	case 'c':
		zn, _ := d.Zone()
		output.WriteString(fmt.Sprintf("%s %02d %s %d %02d:%02d:%02d %s %s",
			getShortWeekday(d.Weekday()),
			d.Day(),
			getShortMonth(d.Month()),
			d.Year(),
			getAMPMHour(d),
			d.Minute(),
			d.Second(),
			getAMPM(d, true),
			zn))
	case 'C', 'g':
		output.WriteString(strconv.Itoa(d.Year())[0:2])
	case 'd':
		output.WriteString(fmt.Sprintf("%02d", d.Day()))
	case 'D':
		output.WriteString(fmt.Sprintf("%02d/%02d/%s", d.Month(), d.Day(), strconv.Itoa(d.Year())[2:4]))
	case 'e':
		if d.Day() >= 10 {
			output.WriteString(strconv.Itoa(d.Day()))
		} else {
			output.WriteString(" " + strconv.Itoa(d.Day()))
		}
	case 'F':
		output.WriteString(fmt.Sprintf("%d-%02d-%02d", d.Year(), d.Month(), d.Day()))
	case 'G':
		output.WriteString(strconv.Itoa(d.Year()))
	case 'H':
		output.WriteString(fmt.Sprintf("%02d", d.Hour()))
	case 'I':
		output.WriteString(fmt.Sprintf("%02d", getAMPMHour(d)))
	case 'j':
		output.WriteString(fmt.Sprintf("%03d", d.YearDay()))
	case 'k':
		output.WriteString(" " + strconv.Itoa(d.Hour()))
	case 'l':
		output.WriteString(strconv.Itoa(getAMPMHour(d)))
	case 'm':
		output.WriteString(fmt.Sprintf("%02d", d.Month()))
	case 'M':
		output.WriteString(fmt.Sprintf("%02d", d.Minute()))
	case 'N':
		output.WriteString(fmt.Sprintf("%09d", d.Nanosecond()))
	case 'p':
		output.WriteString(getAMPM(d, false))
	case 'P':
		output.WriteString(getAMPM(d, true))
	case 'r':
		output.WriteString(fmt.Sprintf("%02d:%02d:%02d %s", getAMPMHour(d), d.Minute(), d.Second(), getAMPM(d, true)))
	case 'R':
		output.WriteString(fmt.Sprintf("%02d:%02d", d.Hour(), d.Minute()))
	case 's':
		output.WriteString(strconv.FormatInt(d.Unix(), 10))
	case 'S':
		output.WriteString(fmt.Sprintf("%02d", d.Second()))
	case 'T':
		output.WriteString(fmt.Sprintf("%02d:%02d:%02d", d.Hour(), d.Minute(), d.Second()))
	case 'u':
		output.WriteString(strconv.Itoa(getWeekdayNum(d)))
	case 'V':
		_, wn := d.ISOWeek()
		output.WriteString(fmt.Sprintf("%02d", wn))
	case 'w':
		output.WriteString(strconv.Itoa(int(d.Weekday())))
	case 'y':
		output.WriteString(strconv.Itoa(d.Year())[2:4])
	case 'Y':
		output.WriteString(strconv.Itoa(d.Year()))
	case 'z':
		output.WriteString(getTimezone(d, false))
	case ':':
		input.ReadRune()
		output.WriteString(getTimezone(d, true))
	case 'Z':
		zn, _ := d.Zone()
		output.WriteString(zn)
	default:
		output.WriteRune('%')
		output.WriteRune(r)
	}
}