How can I extract the value of my current local time offset? - go

I'm struggling a bit trying to format and display some IBM mainframe TOD clock data. I want to format the data in both GMT and local time (as the default -- otherwise in the zone the user specifies).
For this, I need to get the value of the local time offset from GMT as a signed integer number of seconds.
In zoneinfo.go (which I confess I don't fully understand), I can see
// A zone represents a single time zone such as CEST or CET.
type zone struct {
name string // abbreviated name, "CET"
offset int // seconds east of UTC
isDST bool // is this zone Daylight Savings Time?
}
but this is not, I think, exported, so this code doesn't work:
package main
import ( "time"; "fmt" )
func main() {
l, _ := time.LoadLocation("Local")
fmt.Printf("%v\n", l.zone.offset)
}
Is there a simple way to get this information?

You can use the Zone() method on the time type:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
zone, offset := t.Zone()
fmt.Println(zone, offset)
}
Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.

Package time
func (Time) Local
func (t Time) Local() Time
Local returns t with the location set to local time.
func (Time) Zone
func (t Time) Zone() (name string, offset int)
Zone computes the time zone in effect at time t, returning the
abbreviated name of the zone (such as "CET") and its offset in seconds
east of UTC.
type Location
type Location struct {
// contains filtered or unexported fields
}
A Location maps time instants to the zone in use at that time.
Typically, the Location represents the collection of time offsets in
use in a geographical area, such as CEST and CET for central Europe.
var Local *Location = &localLoc
Local represents the system's local time zone.
var UTC *Location = &utcLoc
UTC represents Universal Coordinated Time (UTC).
func (Time) In
func (t Time) In(loc *Location) Time
In returns t with the location information set to loc.
In panics if loc is nil.
For example,
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
// For a time t, offset in seconds east of UTC (GMT)
_, offset := t.Local().Zone()
fmt.Println(offset)
// For a time t, format and display as UTC (GMT) and local times.
fmt.Println(t.In(time.UTC))
fmt.Println(t.In(time.Local))
}
Output:
-18000
2016-01-24 16:48:32.852638798 +0000 UTC
2016-01-24 11:48:32.852638798 -0500 EST

I don't think it makes sense to manually convert time to another TZ. Use time.Time.In function:
package main
import (
"fmt"
"time"
)
func printTime(t time.Time) {
zone, offset := t.Zone()
fmt.Println(t.Format(time.Kitchen), "Zone:", zone, "Offset UTC:", offset)
}
func main() {
printTime(time.Now())
printTime(time.Now().UTC())
loc, _ := time.LoadLocation("America/New_York")
printTime(time.Now().In(loc))
}

Related

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

How to convert timestamp locally according to our location

startTime := time.Unix(logUserDetail[k].LogTime, 0)
startTimeOfLog := startTime.String()[11:16]
I have time in timestamp format and it is in UTC time zone. I want to convert this time to the local timezone according to our location.
logUserDetail[k].LogTime is in timestamp(1499335473)
You can use (t Time) In() (Golang documentation) to convert startTime to use your local timezone.
Please check the Local function for time structs: https://golang.org/pkg/time/#Time.Local
package main
import (
"fmt"
"time"
)
func main() {
startTime := time.Now()
fmt.Println(startTime.Local())
}

Golang time - time zone showing twice

On running this code the result should show date time and zone
Surprisingly the result shows time zone twice and am not able to figure out why
package main
import (
"fmt"
"time"
)
func main() {
mytime, _ := time.Parse("02/Jan/2006:15:04:05 -0700", "07/Apr/2017:01:26:05 +0530")
fmt.Println(mytime)
}
Output of this is
2017-04-07 01:26:05 +0530 +0530
So my question is why timezone showing twice ?
The fmt.Println invokes the Time's .String() function that returns the time in the following format:
"2006-01-02 15:04:05.999999999 -0700 MST"
Which as you see contains both the timezone offset and the timezone name.
In your case there is no timezone name known for the time, so it outputs the offset twice.
References:
https://golang.org/pkg/time/#Time.String

Golang time error: month out of range

Here is my code:
time.Parse(time.Now().String()[0:19],time.Now().String()[0:19])
error:
parsing time "2016-09-20 16:50:08": month out of range
How to parse time string?
First param is layout, see:
func Parse(layout, value string) (Time, error) {
return parse(layout, value, UTC, Local)
}
Docs:
// Parse parses a formatted string and returns the time value it represents.
// The layout defines the format by showing how the reference time,
// defined to be
// Mon Jan 2 15:04:05 -0700 MST 2006
// would be interpreted if it were the value; it serves as an example of
// the input format. The same interpretation will then be made to the
// input string.
//
// Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard
// and convenient representations of the reference time. For more information
// about the formats and the definition of the reference time, see the
// documentation for ANSIC and the other constants defined by this package.
// Also, the executable example for time.Format demonstrates the working
// of the layout string in detail and is a good reference.
//
// Elements omitted from the value are assumed to be zero or, when
// zero is impossible, one, so parsing "3:04pm" returns the time
// corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is
// 0, this time is before the zero Time).
// Years must be in the range 0000..9999. The day of the week is checked
// for syntax but it is otherwise ignored.
//
// In the absence of a time zone indicator, Parse returns a time in UTC.
//
// When parsing a time with a zone offset like -0700, if the offset corresponds
// to a time zone used by the current location (Local), then Parse uses that
// location and zone in the returned time. Otherwise it records the time as
// being in a fabricated location with time fixed at the given zone offset.
//
// No checking is done that the day of the month is within the month's
// valid dates; any one- or two-digit value is accepted. For example
// February 31 and even February 99 are valid dates, specifying dates
// in March and May. This behavior is consistent with time.Date.
//
// When parsing a time with a zone abbreviation like MST, if the zone abbreviation
// has a defined offset in the current location, then that offset is used.
// The zone abbreviation "UTC" is recognized as UTC regardless of location.
// If the zone abbreviation is unknown, Parse records the time as being
// in a fabricated location with the given zone abbreviation and a zero offset.
// This choice means that such a time can be parsed and reformatted with the
// same layout losslessly, but the exact instant used in the representation will
// differ by the actual zone offset. To avoid such problems, prefer time layouts
// that use a numeric zone offset, or use ParseInLocation.
You may use
t, err := time.Parse("2006-01-02 15:04:05", time.Now().String()[:19])
Try on The Go Playground:
package main
import (
"fmt"
"time"
)
func main() {
t, err := time.Parse("2006-01-02 15:04:05", time.Now().String()[:19])
if err != nil {
panic(err)
}
fmt.Println(t)
}
output:
2009-11-10 23:00:00 +0000 UTC
I had the same problem, so I came here to say golang will some times mean "month" they meant "DAY OF THE MONTH", the error message is wrong, here is an example:
package main
import (
"fmt"
"time"
)
func main() {
dateAsString:= "31/Oct/2019"
layout := "01/Jan/2006" // BAD BAD BAD SHOULD BE 02 INSTEAD OF 01
fmt.Println("INPUT:" + dateAsString)
t, err := time.Parse(layout, dateAsString)
if err != nil {
fmt.Println("DATE UNPARSEABLE:3", err)
}
fmt.Println(t)
}

why does time.Parse parse the time incorrectly?

I'm trying to parse a string as time with but unfortunately go gets the wrong month (January instead of June)
package main
import "fmt"
import "time"
func main() {
t := "2014-06-23T20:29:39.688+01:00"
tc, _ := time.Parse("2006-01-02T15:04:05.000+01:00", t)
fmt.Printf("t was %v and tc was %v", t, tc)
}
Play
The problem is that your timezone offset is ill-defined in the layout: the reference offset is -0700. You defined yours as +01:00, so the 01 is interpreted as the month and erase the previously defined one. And as your working offset is 01 as well, it is parsed as january.
The following example works for me playground
package main
import "fmt"
import "time"
func main() {
t := "2014-06-23T20:29:39.688+01:00"
tc, _ := time.Parse("2006-01-02T15:04:05.000-07:00", t)
fmt.Printf("t was %v and tc was %v", t, tc)
}
Your layout string is incorrect. The numbers in the layout string have special meanings, and you are using 1 twice: once in the month portion and once in the time zone portion. The time zone in the string you are parsing is 01:00, so you are storing 1 into the month. This explains why the returned month was January (the first month).
A corrected layout string is 2006-01-02T15:04:05.000-07:00. Or, if you're happy with using Z to represent UTC, the time.RFC3339 constant might be appropriate.

Resources