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
Related
This question already has answers here:
Convert time.Time to string
(6 answers)
Closed 2 years ago.
I want to get a timestamp as string. If I use string conversion I got no error but the output is not readable.
Later, I want us it as a part of a filename.
It looks like a question mark for e.g. �
I found some examples like this: https://play.golang.org/p/bq2h3h0YKp
not solves completely me problem. thanks
now := time.Now() // current local time
sec := now.Unix() // number of seconds since January 1, 1970 UTC
fmt.Println(string(sec))
How could I get the timestamp as string?
Something like this works for me
package main
import (
"fmt"
"strconv"
"time"
)
func main() {
now := time.Now()
unix := now.Unix()
fmt.Println(strconv.FormatInt(unix, 10))
}
Here are two examples of how you can convert a unix timestamp to a string.
The first example (s1) uses the strconv package and its function FormatInt. The second example (s2) uses the fmt package (documentation) and its function Sprintf.
Personally, I like the Sprintf option more from an aesthetic point of view. I did not check the performance yet.
package main
import "fmt"
import "time"
import "strconv"
func main() {
t := time.Now().Unix() // t is of type int64
// use strconv and FormatInt with base 10 to convert the int64 to string
s1 := strconv.FormatInt(t, 10)
fmt.Println(s1)
// Use Sprintf to create a string with format:
s2 := fmt.Sprintf("%d", t)
fmt.Println(s2)
}
Golang Playground: https://play.golang.org/p/jk_xHYK_5Vu
I'm trying to add some values from my database to a []string in Go. Some of these are timestamps.
I get the error:
cannot use U.Created_date (type time.Time) as type string in array element
Can I convert time.Time to string?
type UsersSession struct {
Userid int
Timestamp time.Time
Created_date time.Time
}
type Users struct {
Name string
Email string
Country string
Created_date time.Time
Id int
Hash string
IP string
}
-
var usersArray = [][]string{}
rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute >= now()")
U := Users{}
US := UsersSession{}
for rows.Next() {
err = rows.Scan(&U.Id, &U.Hash, &U.Name, &U.Email, &U.Country, &U.IP, &U.Created_date, &US.Timestamp, &US.Created_date)
checkErr(err)
userid_string := strconv.Itoa(U.Id)
user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date}
// -------------
// ^ this is where the error occurs
// cannot use U.Created_date (type time.Time) as type string in array element (for US.Created_date and US.Timestamp aswell)
// -------------
usersArray = append(usersArray, user)
log.Print("usersArray: ", usersArray)
}
EDIT
I added the following. It works now, thanks.
userCreatedDate := U.Created_date.Format("2006-01-02 15:04:05")
userSessionCreatedDate := US.Created_date.Format("2006-01-02 15:04:05")
userSessionTimestamp := US.Timestamp.Format("2006-01-02 15:04:05")
You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".
If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".
Example:
t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))
Output (try it on the Go Playground):
2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00
Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.
Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():
Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.
package main
import (
"fmt"
"time"
)
// #link https://golang.org/pkg/time/
func main() {
//caution : format string is `2006-01-02 15:04:05.000000000`
current := time.Now()
fmt.Println("origin : ", current.String())
// origin : 2016-09-02 15:53:07.159994437 +0800 CST
fmt.Println("mm-dd-yyyy : ", current.Format("01-02-2006"))
// mm-dd-yyyy : 09-02-2016
fmt.Println("yyyy-mm-dd : ", current.Format("2006-01-02"))
// yyyy-mm-dd : 2016-09-02
// separated by .
fmt.Println("yyyy.mm.dd : ", current.Format("2006.01.02"))
// yyyy.mm.dd : 2016.09.02
fmt.Println("yyyy-mm-dd HH:mm:ss : ", current.Format("2006-01-02 15:04:05"))
// yyyy-mm-dd HH:mm:ss : 2016-09-02 15:53:07
// StampMicro
fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000"))
// yyyy-mm-dd HH:mm:ss: 2016-09-02 15:53:07.159994
//StampNano
fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000000"))
// yyyy-mm-dd HH:mm:ss: 2016-09-02 15:53:07.159994437
}
package main
import (
"fmt"
"time"
)
func main() {
v , _ := time.Now().UTC().MarshalText()
fmt.Println(string(v))
}
Output : 2009-11-10T23:00:00Z
Go Playground
Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.
Package Link: https://github.com/vigneshuvi/GoDateFormat.
Please find the plackholders:https://medium.com/#Martynas/formatting-date-and-time-in-golang-5816112bf098
package main
// Import Package
import (
"fmt"
"time"
"github.com/vigneshuvi/GoDateFormat"
)
func main() {
fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}
func GetToday(format string) (todayString string){
today := time.Now()
todayString = today.Format(format);
return
}
strconv.Itoa(int(time.Now().Unix()))
Go Playground
http://play.golang.org/p/DN5Py5MxaB
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
// The Time type implements the Stringer interface -- it
// has a String() method which gets called automatically by
// functions like Printf().
fmt.Printf("%s\n", t)
// See the Constants section for more formats
// http://golang.org/pkg/time/#Time.Format
formatedTime := t.Format(time.RFC1123)
fmt.Println(formatedTime)
}
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)
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);
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.