udayakumar
udayakumar

Reputation: 665

How to add or sub UTC offset value in current time

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?

Upvotes: 0

Views: 2416

Answers (2)

novalagung
novalagung

Reputation: 11532

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)

Upvotes: 3

udayakumar
udayakumar

Reputation: 665

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

Upvotes: 0

Related Questions