Go TimeFromAge()

Jmnote (토론 | 기여)님의 2025년 11월 21일 (금) 16:30 판 (새 문서: ==개요== ;Go TimeFromAge() <syntaxhighlight lang='go'> func TimeFromAge(age string, currentTime time.Time) (time.Time, error) { re := regexp.MustCompile(`(\d+)([smhd])`) matches...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

개요[ | ]

Go TimeFromAge()
func TimeFromAge(age string, currentTime time.Time) (time.Time, error) {
	re := regexp.MustCompile(`(\d+)([smhd])`)
	matches := re.FindAllStringSubmatch(age, -1)

	if matches == nil {
		return time.Time{}, fmt.Errorf("invalid age format")
	}

	var totalDuration time.Duration

	for _, match := range matches {
		value, err := strconv.Atoi(match[1])
		if err != nil {
			return time.Time{}, err
		}

		unit := match[2]

		duration := time.Duration(value)
		switch unit {
		case "s":
			duration *= time.Second
		case "m":
			duration *= time.Minute
		case "h":
			duration *= time.Hour
		case "d":
			duration *= 24 * time.Hour
		default:
			return time.Time{}, fmt.Errorf("invalid unit: %s", unit)
		}

		totalDuration -= duration
	}

	return currentTime.Add(totalDuration), nil
}
func TestTimeFromAge(t *testing.T) {
	currentTime := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)

	tests := []struct {
		name    string
		age     string
		want    time.Time
		wantErr bool
	}{
		{
			name: "Subtract 3 seconds",
			age:  "3s",
			want: currentTime.Add(-3 * time.Second),
		},
		{
			name: "Subtract 4 hours and 51 minutes",
			age:  "4h51m",
			want: currentTime.Add(-4*time.Hour - 51*time.Minute),
		},
		{
			name: "Subtract 9 days",
			age:  "9d",
			want: currentTime.Add(-9 * 24 * time.Hour),
		},
		{
			name: "Subtract 400 days",
			age:  "400d",
			want: currentTime.Add(-400 * 24 * time.Hour),
		},
		{
			name:    "Invalid age format",
			age:     "invalid",
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := TimeFromAge(tt.age, currentTime)
			if tt.wantErr {
				require.Error(t, err)
				return
			}
			require.NoError(t, err)
			require.Equal(t, tt.want, got)
		})
	}
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}