Time package and time zones/Locations

Hi,

I’m having a tough time understanding the time package. Specifically, how to parse timestamps to a location.
Here is what I have (very basic):-

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {

	p := fmt.Println

	inputedTime := "2017-07-31 10:00:00.000"
	p("Timestamp provided:", inputedTime)

	layout := "2006-01-02 15:04:05.000"
	p("layout provided:", layout)

	tt, err := time.Parse(layout, inputedTime)
	if err != nil {
		log.Println("Err is", err)
	}

	p("CParsed time is: ", tt.String())
	p("Unix time is:", tt.Unix())
	p("Unix Nano time is:", tt.UnixNano())
	p("Unix time ( *100) is:", tt.Unix()*1000)

}

Extremely simple… all I need is to bind the inputedTime to Europe/London or Etc/GMT or Etc/GMT+1 and so on.

I am working with an application which will only accept Unix time timestamps in it’s DSL/Query language. I am collecting timestamps from the user with the flags package (thats all working fine) but I am finding some oddities when using Unix time when the timestamp has not been parsed with the location in mind.

Would appreciate any pointers or simple examples to help me to see how to Parse timestamps in a Location aware way.

Thanks!

This looks better. Is it correct?

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {

	p := fmt.Println

	loc, _ := time.LoadLocation("Europe/London")
		if err != nil {
		log.Println("Err is", err)
	}

	inputedTime := "2017-07-31 10:00:00.000"
	p("Timestamp provided:", inputedTime)

	layout := "2006-01-02 15:04:05.000"
	p("layout provided:", layout)

	tt, err := time.ParseInLocation(layout, inputedTime, loc)
	if err != nil {
		log.Println("Err is", err)
	}

	p("Parsed time is: ", tt.String())
	p("Unix time is:", tt.Unix())
	p("Unix Nano time is:", tt.UnixNano())
	p("Unix time ( *1000) is:", tt.Unix()*1000)

}

The resultant time value does appear to have been adjusted for the +0100 due to current BST.

Thanks.

Looks good to me. If the time strings do not contain time zone information, LoadLocation is a way of specifying the current time zone as a reference for interpreting parsed time strings.

@christophberger

Thank you very much for looking.
The basis of this technique is now working beautifully for me in the application.

This seems to be the way I’m progressing with Go … stuck. Stuck. STUCK!! … Oh… right, actually it’s easy.

Thanks again.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.