Reputation: 973
I know we need to use the time.Time interface for dates in Go.
And to format, we need to use the format function.
http://golang.org/pkg/time/#Time.Format
But what are the valid and different formatters available for time.Time in Golang?
Upvotes: 4
Views: 13298
Reputation: 143
In case you need custom layout and/or struggling with build in layouts.
type Rtime struct {
Year int
Month int
Day int
Hour int
Minute int
Second int
Nanosecond int
Millisecond int
Offset int
OffsetString string
Zone string
}
func (rt *Rtime) LocalNow() {
t := time.Now()
rt.Hour,rt.Minute,rt.Second = t.Clock()
rt.Nanosecond = t.Nanosecond()
rt.Millisecond = rt.Nanosecond / 1000000
rt.Month = int(t.Month())
rt.Day = t.Day()
rt.Year = t.Year()
rt.OffsetString = ""
rt.Zone, rt.Offset = t.Local().Zone()
if rt.Offset > 0 {
rt.OffsetString = fmt.Sprintf("+%02d%02d",
rt.Offset/(60*60),
rt.Offset%(60*60)/60)
} else {
rt.OffsetString = fmt.Sprintf("%02d%02d",
rt.Offset/(60*60),
rt.Offset%(60*60)/60)
}
}
str := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d.%03d %s %s %d",
rt.Year,rt.Month,rt.Day,rt.Hour,rt.Minute,rt.Second,
rt.Millisecond,rt.Zone,rt.OffsetString,rt.Nanosecond)
fmt.Println(str)
output
2021-06-06 09:21:54.949 EEST +0300 949861778
Upvotes: 0
Reputation: 651
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
fmt.Println(t.Format(time.Kitchen))
t := time.Now()
tf := t.Format("2006-01-02 15:04:05-07:00")
fmt.Println(tf)
}
Upvotes: 2
Reputation: 1740
The docs for time.Format say http://golang.org/pkg/time/#Time.Format:
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.
So, in the constants http://golang.org/pkg/time/#pkg-constants:
To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.
In short: you write the reference time Mon Jan 2 15:04:05 MST 2006
in the format you want and pass that string to Time.Format()
As @Volker said, please read the docs and read about the difference between types and interfaces.
Upvotes: 5
Reputation: 973
Golang prescribes different standards to be followed for getting valid dates.
Available in http://golang.org/pkg/time/#Time.Format
Upvotes: -1