0

How can I add or subtract UTC offset (Another time location) value in my current time in GoLang. I tried this link but no use (example)

Example

  1. My input is "UTC+7". I don't know the location. Now I'm in India.
  2. Now I'm getting India (IST) time. Ex: 2019-07-23T15:23:08, Here I need to add UTC+7 in IST. It's possible?
udayakumar
  • 639
  • 1
  • 7
  • 16
  • Possible duplicate of [Subtracting time.Duration from time in Go](https://stackoverflow.com/questions/26285735/subtracting-time-duration-from-time-in-go) – mkopriva Jul 23 '19 at 10:44
  • How about `t.UTC()` try [this: `fmt.Println(t.UTC())`](https://play.golang.org/p/mqeJh6c9SWJ) – wasmup Jul 23 '19 at 11:00
  • @Adam, It is okay but I need IST current time changed to Indonesia time using UTC+7. – udayakumar Jul 23 '19 at 11:04
  • 3
    To make your question clear, you need to add sample inputs and desired outputs. – wasmup Jul 23 '19 at 11:09

2 Answers2

3

Use time.LoadLocation() to get location information of particular timezone. Then use the .In() method of time object, to convert the current time into expected timezone.

Example:

now := time.Now()
fmt.Println("My place", now)
// 2019-07-23 18:14:23.6036439 +0700 +07

locSingapore, _ := time.LoadLocation("Asia/Singapore")
nowInSingapore := now.In(locSingapore)
fmt.Println("Singapore", nowInSingapore)
// 2019-07-23 19:14:23.6036439 +0800

locLondon, _ := time.LoadLocation("Europe/London")
nowInLondon := now.In(locLondon)
fmt.Println("London", nowInLondon)
// 2019-07-23 12:14:23.6036439 +0100 BST

Explanations:

  • From code above we can see that time.Now() timezone is +7, it's because I live in West Indonesia.
  • But nowInSingapore timezone is +8, it's because the now object are adjusted into singapore timezone.
  • And the last one, nowInLondon is showing another different timezone, +1.

And if we compare all of those time, it's essentially same time.

18:14:23 WIB (GMT +7) == 19:14:23 GMT +8 == 12:14:23 BST (GMT +1)

novalagung
  • 10,905
  • 4
  • 58
  • 82
0

I Solved the issue.

now := time.Now()

fmt.Println("now:", now.Format("2006-01-02T15:04:05"))

UTC_String_Value := "UTC+7"

UTC_Split_Value := strings.Split(UTC_String_Value, "+")


count, err := strconv.Atoi(UTC_Split_Value [1])
if err != nil {
    fmt.Println(err)
}

resp := now.Add(time.Duration(-count) * time.Hour).Format("2006-01-02T15:04:05") 
//Subract the utc offset value 7 (hours)


fmt.Println("now:", now.Format("2006-01-02T15:04:05"))
fmt.Println("resp:", resp)

Output

now: 2019-07-24T11:25:17
resp: 2019-07-24T04:25:17
udayakumar
  • 639
  • 1
  • 7
  • 16