How to add or sub UTC offset value in current time - go

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
My input is "UTC+7". I don't know the location. Now I'm in India.
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?

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)

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

Related

Subtracting time to get age

My aim is to calculate the age of the pod by doing the subtraction of "current_time - pod_creation_time" so that I will get the age, I am getting creation time from metadata but it's in the format "2021-07-13 16:34:22 +0530 IST", so when I trying to subtract it from time.Now(), I am getting parsing error like below:
invalid operation: "t2 : " + t2 (mismatched types string and time.Time)
Anyone could please help how to have creation time "2021-07-13 16:34:22 +0530 IST" from metadata in the proper format so that I can do "time.Now - (creation time)"
I tried some workaround like below:
creatTime, err := time.Parse("2006-01-02 15:04:05 -0700 MST",
pod.ObjectMeta.CreationTimestamp.String())
and then subtracted creationTime from Current Time. It works, but I think this is not the right way.
There's a type mismatch as time.Now() return the current time stored in the type time.Time whereas 2021-07-13 16:34:22 +0530 IST is a string. You can perform the required subtraction operation on mismatched types i.e., time.Time and string.
You have to parse the string by specifying the layout. I'd recommend reading the time package's doc.
I've explained every operation in the sample code below; I hope it helps. If you understand this, you can also then look at helper functions like time.Since that can help you write the same program in fewer lines.
package main
import (
"fmt"
"time"
)
func main() {
// K8s timestamp
t := "2021-07-13 16:34:22 +0530 IST"
// Format of K8s timestamp
format := "2006-01-02 15:04:05 -0700 MST" // Mon Jan 2 15:04:05 -0700 MST 2006
// Parse the timestamp so that it's stored in time.Time
cur, err := time.Parse(format, t)
if err != nil {
panic(err)
}
// Current time
now := time.Now()
// As both are of type time.Time, it's subtractable
dur := now.Sub(cur)
// Print duration
fmt.Println(dur)
// Print duration (in seconds)
fmt.Println(dur.Seconds())
}
Also, I'd like you to learn how to write questions on StackOverflow. The formatting of your question is pretty bad. When seeking good solutions; it is the OP's duty to post the question correctly first so that everybody could understand it and then expect answers.
Read: https://stackoverflow.com/help/how-to-ask

Go parse time to string and back

I am trying to do something in Go that is very simple in languages like Java
I want to parse current time to string and then parse it back to time.
This is the code I tried but as can be seen here it gives unexpected results.
I am facing two problems
time.Now().String() gives a wrong date
If I cast the time to string
and cast it back to time, it gives a totally different date.
What is the right (and easy) way to do this?
p := fmt.Println
startStr := time.Now().String() //2009-11-10 23:00:00 +0000 UTC m=+0.000000001
p(startStr)
startTime, _ := time.Parse(
"2009-11-10 23:00:00 +0000 UTC m=+0.000000001",
startStr)
p(startTime) //0001-01-01 00:00:00 +0000 UTC
time.Now().String() is meant for debugging only (see go doc).
You should instead use time.Format().
For example:
p := fmt.Println
now := time.Now().Format(time.RFC3339)
p(now)
parsed, _ := time.Parse(time.RFC3339, now)
p(parsed.Format(time.RFC3339))
produces:
2009-11-10T23:00:00Z
2009-11-10T23:00:00Z
Your other concern regarding time.Now().String() gives a wrong date is likely due to where you're running the code. e.g. if you're running in "The Go Playgounrd", then the time won't be accurate. You should run it on your own computer, and assuming your computer has the correct time, then you should get the right time printed.
Unlike some other languages, Go does not treat String() as a de facto marshaling method -- instead, it's meant just to print the value out for debugging purposes. You could parse back from that format into a Time if you used a proper format string; however, a proper format string must be for the exact time of Mon Jan 2 15:04:05 MST 2006, not any time; but the format that String() prints out isn't captured by a constant within the Time package so it's probably not worth doing.
Instead, however, what you're trying to do may be better captured by the MarshalText and UnmarshalText methods:
startStr, _ := time.Now().MarshalText()
fmt.Println(string(startStr)) // 2009-11-10T23:00:00Z
startTime := new(time.Time)
startTime.UnmarshalText(startStr)
fmt.Println(startTime) // 2009-11-10 23:00:00 +0000 UTC
The time in the playground is fixed, it is always the date and time of
the Go announcement.
https://github.com/golang/go/issues/10663
So to play with time correctly, you need to run it on your local.
About the parsing time to string or back, you have to pass the format of time string:
For example:
package main
import (
"fmt"
"time"
)
func main() {
current := time.Now()
fmt.Println("Init Time:", current.String())
timeCustomFormatStr := current.Format("2006-01-02 15:04:05 -0700")
fmt.Println("Custom format", timeCustomFormatStr)
parsedTime, err := time.Parse("2006-01-02 15:04:05 -0700",timeCustomFormatStr)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("parsedTime From Custom:", parsedTime)
timeFormatRFC3339 := current.Format(time.RFC3339)
fmt.Println("RFC3339 format", timeFormatRFC3339)
parsedTimeRFC3339, err := time.Parse(time.RFC3339,timeFormatRFC3339)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("parsedTime From Custom:", parsedTimeRFC3339)
}
Ref:
1 https://golang.org/pkg/time/#Time.Format

IST time zone error in time package go golang

I need to convert any given time zone in RFC3339 format to system time in RFC3339 format.But for few time zone like IST it is throwing the error and the time is still in UTC.
For conversion which function service as better? time.parse or time.In.
I tried to convert the UTC to IST but it failed.
package main
import (
"fmt"
"time"
)
func main() {
//now time
now := time.Now()
fmt.Println("now ", now)
zone, _ := now.Zone()
fmt.Println("zone->", zone)
ll, llerr := time.LoadLocation(zone)
fmt.Println("Load Location", ll, llerr)
// Convert the given time to system based time zone
t, err := time.ParseInLocation(time.RFC3339, "2017-04-25T23:03:00Z", ll)
fmt.Println("t - parsein", t)
fmt.Println("err - parsein", err)
//fmt.Println("t2 - parse", t.In(ll))
}
Error : unknown time zone IST
Expected: Need to convert any time zone to system time zone.
You can't load Indian IST time zone by that name because the name "IST" is ambiguous. It could mean India, Ireland, Israel, etc. time zones, which have different zone offsets and rules. For details, see Why is time.Parse not using the timezone?
If IST is your local zone, the time.Local variable will denote that time zone. If you have a time.Time, you can "switch" to another zone using Time.In(), also Time.Local() returns the time in your local zone.
Of course this code would "break" when ran in another zone. To make sure it behaves the same everywhere, load the Indian IST zone explicitly like this:
loc, err := time.LoadLocation("Asia/Kolkata")
if err != nil {
panic(err)
}
fmt.Println(time.Now())
fmt.Println(time.Now().In(loc))
On the Go Playground it will output:
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009-11-11 04:30:00 +0530 IST

Convert timestamp to ISO format in golang

I'm trying to convert the timestamp 2018-12-17T15:03:49.000+0000 to ISO format in golang, but am getting an error cannot parse "+0000" as "Z07:00"
This is what I tried
ts, err := time.Parse(time.RFC3339, currentTime)
Any ideas?
Beware, a long answer ahead
(tl;dr) use:
ts, err := time.Parse("2006-01-02T15:04:05-0700", currentTime)
ts.Format(time.RFC3339)
I really like go documentation, and you should do :)
All from https://golang.org/pkg/time/#pkg-constants
RFC3339 = "2006-01-02T15:04:05Z07:00"
Some valid layouts are invalid time values for time.Parse, due to
formats such as _ for space padding and Z for zone information
Which means you can't parse +0000 with layout Z07:00.
Also:
The reference time used in the layouts is the specific time:
Mon Jan 2 15:04:05 MST 2006
which is Unix time 1136239445. Since MST is GMT-0700, the reference
time can be thought of as
01/02 03:04:05PM '06 -0700
You can either parse numeric time zone offsets format as follows:
-0700 ±hhmm
-07:00 ±hh:mm
-07 ±hh
Or replacing the sign in the format with a Z:
Z0700 Z or ±hhmm
Z07:00 Z or ±hh:mm
Z07 Z or ±hh
fraction:
From this go example https://play.golang.org/p/V9ubSN6gTdG
// If the fraction in the layout is 9s, trailing zeros are dropped.
do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
So you can parse it like:
ts, err := time.Parse("2006-01-02T15:04:05.999-0700", currentTime)
Also, From the doc
A decimal point followed by one or more zeros represents a fractional
second, printed to the given number of decimal places. A decimal point
followed by one or more nines represents a fractional second, printed
to the given number of decimal places, with trailing zeros removed.
When parsing (only), the input may contain a fractional second field
immediately after the seconds field, even if the layout does not
signify its presence. In that case a decimal point followed by a
maximal series of digits is parsed as a fractional second.
Which means you can leave out the decimal points from the layout and it will parse correctly
ts, err := time.Parse("2006-01-02T15:04:05-0700", currentTime)
For getting the time in UTC simply write ts.UTC()
And for formatting it to RFC3339, you can use
ts.Format(time.RFC3339)
Example
currentTime := "2018-12-17T17:02:04.123+0530"
ts, err := time.Parse("2006-01-02T15:04:05-0700", currentTime)
if err != nil {
panic(err)
}
fmt.Println("ts: ", ts)
fmt.Println("ts in utc: ", ts.UTC())
fmt.Println("RFC3339: ", ts.Format(time.RFC3339))
// output
// ts: 2018-12-17 17:02:04.123 +0530 +0530
// ts in utc: 2018-12-17 11:32:04.123 +0000 UTC
// RFC3339: 2018-12-17T17:02:04+05:30
playground: https://play.golang.org/p/vfERDm_YINb
How about this?
ts, err := time.Parse("2006-01-02T15:04:05.000+0000", currentTime)
since time.RFC3339 is just 2006-01-02T15:04:05Z07:00

How to check whether current local time is DST?

In Ruby, for example, there's the Time#dst? function, which returns true in the case it is daylight saving time. Is there a Go standard library API call to do the same?
In August 2021 go 1.17 was released which now adds the time.Time method IsDST:
IsDST reports whether the time in the configured location is in
Daylight Savings Time.
The Location api doesn't export the DST value of the timezone. This was brought up in the golang-nuts forum several years ago. One suggestion is to compare the January 1 timezone offset to the July 1 timezone offset. A working solution of this was posted using this method. One caveat is that goplay has the wrong local time, so it doesn't correctly report the information if you run it there. You can run it locally to verify that it does work.
Another way would be to use reflection via the reflect package. A solution that I wrote to do this is available here. There are a lot of problems with this method.
Edit: Really it should probably use cacheZone but does a linear search of the zones to find one that matches. This can lead to errors because some timezones share name and offset. The correct way would be to look at cacheZone and use that if it is set. Otherwise, you'll need to either look at zoneTrans or at least look at how lookup(int64) is implemented.
You can infer the result. For example,
package main
import (
"fmt"
"time"
)
// isTimeDST returns true if time t occurs within daylight saving time
// for its time zone.
func isTimeDST(t time.Time) bool {
// If the most recent (within the last year) clock change
// was forward then assume the change was from std to dst.
hh, mm, _ := t.UTC().Clock()
tClock := hh*60 + mm
for m := -1; m > -12; m-- {
// assume dst lasts for least one month
hh, mm, _ := t.AddDate(0, m, 0).UTC().Clock()
clock := hh*60 + mm
if clock != tClock {
if clock > tClock {
// std to dst
return true
}
// dst to std
return false
}
}
// assume no dst
return false
}
func main() {
pstLoc, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
fmt.Println(err)
return
}
utc := time.Date(2018, 10, 29, 14, 0, 0, 0, time.UTC)
fmt.Println(utc, utc.Location(), ": DST", isTimeDST(utc))
local := utc.In(time.Local)
fmt.Println(local, local.Location(), ": DST", isTimeDST(local))
pst := utc.In(pstLoc)
fmt.Println(pst, pst.Location(), ": DST", isTimeDST(pst))
utc = utc.AddDate(0, 3, 0)
fmt.Println(utc, utc.Location(), ": DST", isTimeDST(utc))
local = utc.In(time.Local)
fmt.Println(local, local.Location(), ": DST", isTimeDST(local))
pst = utc.In(pstLoc)
fmt.Println(pst, pst.Location(), ": DST", isTimeDST(pst))
}
Output:
2018-10-29 14:00:00 +0000 UTC UTC : DST false
2018-10-29 10:00:00 -0400 EDT Local : DST true
2018-10-29 07:00:00 -0700 PDT America/Los_Angeles : DST true
2019-01-29 14:00:00 +0000 UTC UTC : DST false
2019-01-29 09:00:00 -0500 EST Local : DST false
2019-01-29 06:00:00 -0800 PST America/Los_Angeles : DST false

Resources