jz22
jz22

Reputation: 2658

How to create day based timestamps

I need to write a function that takes a timestamp in seconds and converts it to a day based timestamp. For example, both timestamps 1584875408 (22/03/2020 11:10am) and 1584872571 (22/03/2020 10:22am) should be transformed to 1584835200 (22/03/2020 12:00am).

I came up with the following function. Besides that it does not work, I think there is a much more clever way to achieve the described behaviour.

func formatTimestamp(t int64) (int64, error) {
    timestamp := time.Unix(t, 0)

    day := timestamp.Format("2006-01-02")

    formatted, err := time.Parse(day, "2006-01-02")
    if err != nil {
        return 0, err
    }

    return formatted.Unix(), nil
}

func main() {
    t, _ := formatTimestamp(1584873099)
    fmt.Println(t)
}

Upvotes: 1

Views: 50

Answers (1)

agermain
agermain

Reputation: 122

The problem is you got the arguments mixed up on time.Parse.

It should be: formatted, err := time.Parse("2006-01-02", day)

Upvotes: 1

Related Questions