Reputation: 665
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
Upvotes: 0
Views: 2416
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:
time.Now()
timezone is +7
, it's because I live in West Indonesia.nowInSingapore
timezone is +8
, it's because the now
object are adjusted into singapore timezone.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
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