Skip to content

Commit

Permalink
Fix week number. (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
ncruces authored May 12, 2023
1 parent 547681d commit 2d545c8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
22 changes: 9 additions & 13 deletions appenders.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ var (
secondsNumberZeroPad = StdlibFormat("05")
hms = StdlibFormat("15:04:05")
tab = Verbatim("\t")
weekNumberSundayOrigin = weeknumberOffset(0) // week number of the year, Sunday first
weekNumberSundayOrigin = weeknumberOffset(true) // week number of the year, Sunday first
weekdayMondayOrigin = weekday(1)
// monday as the first day, and 01 as the first value
weekNumberMondayOriginOneOrigin = AppendFunc(appendWeekNumber)
eby = StdlibFormat("_2-Jan-2006")
// monday as the first day, and 00 as the first value
weekNumberMondayOrigin = weeknumberOffset(1) // week number of the year, Monday first
weekNumberMondayOrigin = weeknumberOffset(false) // week number of the year, Monday first
weekdaySundayOrigin = weekday(0)
natReprTime = StdlibFormat("15:04:05") // national representation of the time XXX is this correct?
natReprDate = StdlibFormat("01/02/06") // national representation of the date XXX is this correct?
Expand Down Expand Up @@ -243,20 +243,16 @@ func (v weekday) Append(b []byte, t time.Time) []byte {
return append(b, byte(n+48))
}

type weeknumberOffset int
type weeknumberOffset bool

func (v weeknumberOffset) Append(b []byte, t time.Time) []byte {
yd := t.YearDay()
offset := int(t.Weekday()) - int(v)
if offset < 0 {
offset += 7
offset := int(t.Weekday())
if v {
offset = 6 - offset
} else if offset != 0 {
offset = 7 - offset
}

if yd < offset {
return append(b, '0', '0')
}

n := ((yd - offset) / 7) + 1
n := (t.YearDay() + offset) / 7
if n < 10 {
b = append(b, '0')
}
Expand Down
24 changes: 24 additions & 0 deletions strftime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,3 +377,27 @@ func TestFormat12AM(t *testing.T) {
return
}
}

func TestFormat_WeekNumber(t *testing.T) {
for y := 2000; y < 2020; y++ {
sunday := "00"
monday := "00"
for d := 1; d < 8; d++ {
base := time.Date(y, time.January, d, 0, 0, 0, 0, time.UTC)

switch base.Weekday() {
case time.Sunday:
sunday = "01"
case time.Monday:
monday = "01"
}

if got, _ := strftime.Format("%U", base); got != sunday {
t.Errorf("Format(%q, %d) = %q, want %q", "%U", base.Unix(), got, sunday)
}
if got, _ := strftime.Format("%W", base); got != monday {
t.Errorf("Format(%q, %d) = %q, want %q", "%W", base.Unix(), got, monday)
}
}
}
}

0 comments on commit 2d545c8

Please sign in to comment.