From 606d053844deae703b1c8e6057e32235b1152c58 Mon Sep 17 00:00:00 2001 From: Radu Ioan Fericean Date: Wed, 31 Jul 2013 14:45:46 +0300 Subject: [PATCH] better parse date --- utils/coreutils.go | 15 +++++++-------- utils/utils_test.go | 8 ++++++++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/utils/coreutils.go b/utils/coreutils.go index fb41718bc..4c5da1650 100644 --- a/utils/coreutils.go +++ b/utils/coreutils.go @@ -19,13 +19,13 @@ along with this program. If not, see package utils import ( - "bytes" "crypto/rand" "crypto/sha1" "encoding/hex" "fmt" "math" "strconv" + "strings" "time" ) @@ -97,22 +97,21 @@ func Round(x float64, prec int, method string) float64 { } func ParseDate(date string) (expDate time.Time, err error) { - expirationTime := []byte(date) switch { - case string(expirationTime) == "*unlimited" || string(expirationTime) == "": + case date == "*unlimited" || date == "": // leave it at zero - case string(expirationTime[0]) == "+": - d, err := time.ParseDuration(string(expirationTime[1:])) + case string(date[0]) == "+": + d, err := time.ParseDuration(date[1:]) if err != nil { return expDate, err } expDate = time.Now().Add(d) - case string(expirationTime) == "*monthly": + case date == "*monthly": expDate = time.Now().AddDate(0, 1, 0) // add one month - case bytes.Contains(expirationTime, []byte("Z")): + case strings.Contains(date, "Z"): expDate, err = time.Parse(time.RFC3339, date) default: - unix, err := strconv.ParseInt(string(expirationTime), 10, 64) + unix, err := strconv.ParseInt(date, 10, 64) if err != nil { return expDate, err } diff --git a/utils/utils_test.go b/utils/utils_test.go index 318611fb0..20efa7c47 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -143,6 +143,14 @@ func TestParseDateEmpty(t *testing.T) { } } +func TestParseDatePlus(t *testing.T) { + date, err := ParseDate("+20s") + expected := time.Now() + if err != nil || date.Sub(expected).Seconds() > 20 || date.Sub(expected).Seconds() < 19 { + t.Error("error parsing date: ", date.Sub(expected).Seconds()) + } +} + func TestParseDateMonthly(t *testing.T) { date, err := ParseDate("*monthly") expected := time.Now().AddDate(0, 1, 0)