Seb
Seb

Reputation: 3215

Week number based on timestamp with Go

I am trying to get the week number based on the timestamp using GoLang.

ts is a int64 and converted

tm := time.UTUnix(ts, 0)
year := tm.Year()
week_nb := ???

for history ts has been generated using:

ts := time.Now().UTC().Unix()

I sent it to a gRPC based server and the server translate it to week number and year.

Any body knows who to convert a ts to a weeknumber ? time library already allow me to get the year but not the week

Thanks

Upvotes: 15

Views: 13513

Answers (1)

peterSO
peterSO

Reputation: 166569

Package time

import "time" 

func (Time) ISOWeek

func (t Time) ISOWeek() (year, week int)

ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.


For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    tn := time.Now().UTC()
    fmt.Println(tn)
    year, week := tn.ISOWeek()
    fmt.Println(year, week)

    ts := time.Now().UTC().Unix()
    tn = time.Unix(ts, 0)
    fmt.Println(tn)
    year, week = tn.ISOWeek()
    fmt.Println(year, week)
}

Playground: https://play.golang.org/p/CjfPscwYXf

Output:

2009-11-10 23:00:00 +0000 UTC
2009 46
2009-11-10 23:00:00 +0000 UTC
2009 46

Upvotes: 29

Related Questions