Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct (short) week string result when set start of week #203

Merged
merged 2 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
}
}