Skip to content

Commit

Permalink
Correct (short) week string result when set start of week (#203)
Browse files Browse the repository at this point in the history
Close #200
  • Loading branch information
gouguoyin authored Nov 30, 2023
2 parents 731fdcb + 760c884 commit 004e90d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
10 changes: 7 additions & 3 deletions outputer.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ func (c Carbon) ToWeekString(timezone ...string) string {
// ToShortWeekString outputs a string in short week layout like "Sun", i18n is supported.
// 输出缩写星期字符串,支持i18n
func (c Carbon) ToShortWeekString(timezone ...string) string {
return c.toWeekString("short_weeks", timezone)
}

func (c Carbon) toWeekString(resourceKey string, timezone []string) string {
if len(timezone) > 0 {
c.loc, c.Error = getLocationByTimezone(timezone[0])
}
Expand All @@ -101,10 +105,10 @@ func (c Carbon) ToShortWeekString(timezone ...string) string {
if len(c.lang.resources) == 0 {
c.lang.SetLocale(defaultLocale)
}
if months, ok := c.lang.resources["short_weeks"]; ok {
if months, ok := c.lang.resources[resourceKey]; ok {
slice := strings.Split(months, "|")
if len(slice) == 7 {
return slice[c.Week()]
if len(slice) == DaysPerWeek {
return slice[c.DayOfWeek()%DaysPerWeek]
}
}
return ""
Expand Down
21 changes: 20 additions & 1 deletion outputer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package carbon

import (
"fmt"
"github.com/stretchr/testify/assert"
"strconv"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestCarbon_String(t *testing.T) {
Expand Down Expand Up @@ -1789,3 +1790,21 @@ func TestCarbon_ToStdTime(t *testing.T) {
actual := Now().ToStdTime().Format(DateTimeLayout)
assert.Equal(t, expected, actual)
}

func TestCarbon_Issue200(t *testing.T) {
assert := assert.New(t)

tests := []struct {
input Carbon
expectedWeekString string
expectedShortWeekString string
}{
{Now().StartOfWeek(), "Sunday", "Sun"},
{Now().SetWeekStartsAt(Monday).StartOfWeek(), "Monday", "Mon"},
{Now().SetWeekStartsAt(Wednesday).StartOfWeek(), "Wednesday", "Wed"},
}
for index, test := range tests {
assert.Equal(test.expectedWeekString, test.input.ToWeekString(), "Current test index is "+strconv.Itoa(index))
assert.Equal(test.expectedShortWeekString, test.input.ToShortWeekString(), "Current test index is "+strconv.Itoa(index))
}
}

0 comments on commit 004e90d

Please sign in to comment.