How to extract unix timestamp and get date - go

I have an integer
x := 1468540800
I want to fetch the date out of this unix timestamp in Golang. I have tried time.ParseDuration but looks like that's not the correct way to extract date out of this. Converstion should happen like this http://www.unixtimestamp.com/index.php
I intend to convert into in ISO 8601 format may be. I want string like 2016-09-14.

You may use t := time.Unix(int64(x), 0) with location set to local time.
Or use t := time.Unix(int64(x), 0).UTC() with the location set to UTC.
You may use t.Format("2006-01-02") to format,
Code (try on The Go Playground):
package main
import (
"fmt"
"time"
)
func main() {
x := 1468540800
t := time.Unix(int64(x), 0).UTC() //UTC returns t with the location set to UTC.
fmt.Println(t.Format("2006-01-02"))
}
output:
2016-07-15

Use time.Unix with nanoseconds set to 0.
t := time.Unix(int64(x), 0)
Playground: https://play.golang.org/p/PpOv8Xm-CS.

You can use strconv.ParseInt() for parsing to int64 in combination with time.Unix.
myTime,errOr := strconv.ParseInt(x, 10, 64)
if errOr != nil {
panic(errOr)
}
newTime := time.Unix(myTime, 0)

$timestamp=1468540800;
echo gmdate("Y-m-d", $timestamp);

Related

How to parse timestamp with underscores in Golang

I'm trying to parse access log timestamp like "2020/11/06_18:17:25_455" in Filebeat according to Golang spec.
Here is my test program to verify layout:
package main
import (
"fmt"
"log"
"time"
)
func main() {
eventDateLayout := "2006/01/02_15:04:05_000"
eventCheckDate, err := time.Parse(eventDateLayout, "2020/11/06_18:17:25_455")
if err != nil {
log.Fatal(err)
}
fmt.Println(eventCheckDate)
}
Result:
2009/11/10 23:00:00 parsing time "2020/11/06_18:17:25_455" as
"2006/01/02_15:04:05_000": cannot parse "455" as "_000"
As I understand underscore has a special meaning in Golang, but from documentation it's not clear how to escape it.
Any ideas, please?
It doesn't seem possible to use any escape characters for the time layout (e.g. "\\_" doesn't work), so one would have to do something different.
This issue describes the same problem, but it was solved in a very non-general way that doesn't seem to apply to your format.
So your best bet seems to be replacing _ with something else/stripping it from the string, then using a layout without it. To make sure that the millisecond part ist also parsed, it must be separated with a . instead of _, then it's recognized as part of the seconds (05) format.
eventDateLayout := "2006/01/02.15:04:05"
val := strings.Replace("2020/11/06_18:17:25_455", "_", ".", 2)
eventCheckDate, err := time.Parse(eventDateLayout, val)
if err != nil {
panic(err)
}
fmt.Println(eventCheckDate)
Playground link
From time.Format
A fractional second is represented by adding a period and zeros to the
end of the seconds section of layout string, as in "15:04:05.000" to
format a time stamp with millisecond precision.
You cannot specify millisecond precision with an underscore you need 05.000 instead:
// eventDateLayout := "2006/01/02_15:04:05_000" // invalid format
eventDateLayout := "2006/01/02_15:04:05.000"
eventCheckDate, err := time.Parse(eventDateLayout, "2020/11/06_18:17:25.455")
So basically use a simple translate function to convert the final _ to a . and use the above parser.
https://play.golang.org/p/POPgXC_qe81

Formatting Go time with Z precision

I have the following Go code:
now := time.Now().UTC().String()
log.Info("time is: " + now)
When this runs it prints out:
time is: 2020-08-21 10:34:43.3547088 +0000 UTC
I only want time precision in HH:mm:ss such that it would print out as:
time is: 2020-08-21 10:34:43Z
What do I need to change to format my time correctly? Must contain that "Z" at the end.
You can use time format to get time as what you want.
func main() {
now := time.Now().UTC().Format("2006-01-02 15:04:05Z")
fmt.Println("time is: " + now)
}
in playground
The format you are trying to print is not from one of the standard formats defined in the time package. Its so close to RFC3339 barring the T notation. But still Format() function allows you to provide a custom format string to show how your time should be printed.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now().UTC()
fmt.Printf("time is: %v", now.Format("2006-01-02 15:04:05Z"))
//fmt.Println("time is: " + now)
}
now := time.Now().UTC().Format("2006-01-02 15:04:05Z")
log.Info("time is: " + now)
ref: https://dev.to/mahbubzulkarnain/golang-time-format-22j0

Easy way to receive a string from day from time.Now()

I'm trying to get the day as a string from a time.Now() instance.
now := time.Now() // .String() would give me the entire date as a string which I don't need
day := now.Day()) // is what I want but as a String.
So string(day) tells me "can not convert day to string".
For me now.Day().String() would be nice but there is no such method...
I could now try to take time.Now().String() and manipulate until the day is left over. But there should be a easier way to do it...
Use strconv to convert int to string
strconv.Itoa(day)
You can import and use strconv as KibGzr mentioned. Just to give a complete example:
package main
import (
"fmt"
"time"
"strconv"
)
func main() {
now := time.Now()
day := now.Day()
fmt.Printf("%T\n",(day))
fmt.Println(strconv.Itoa(day))
dayString := strconv.Itoa(day)
fmt.Printf("%T",(dayString))
}
https://play.golang.org/p/Mqs24FJhCoi

Go: How to parse only date to time.Time?

I want to parse only date value to time.Time.
For example I have date in this format: 2016-03-31, and I want to parse it, like: time.Parse(FORMAT, "2016-03-31").
But it always fail.
What is the correct format string to use to parse only date with this format?
I have the code below as example, it is on playground also: https://play.golang.org/p/0MNLr9emZd
package main
import (
"fmt"
"time"
)
var dateToParse = "2016-03-31"
func main() {
format := "2006-12-01"
parseDate(format)
}
func parseDate(format string) {
t, err := time.Parse(format, dateToParse)
if err != nil {
fmt.Println("Format:", format)
fmt.Println(err)
fmt.Println("")
return
}
fmt.Println("Works Format:", format)
fmt.Println(t)
fmt.Println("")
}
The output is this:
Format: 2006-12-01
parsing time "2016-03-31" as "2006-12-01": cannot parse "-31" as "2"
Package time
These are predefined layouts for use in Time.Format and Time.Parse.
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
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.
Use format := "2006-01-02" for yyyy-mm-dd.
The new format DateOnly = "2006-01-02" of format.go will be added in the Go next release (1.20) per proposal time: add DateTime, DateOnly, TimeOnly format constants and commit
time.Parse(time.DateOnly, dateToParse)

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())
}

Resources