Convert timestamp as string [duplicate] - go

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

Related

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

Get a character by its position in a string [duplicate]

This question already has an answer here:
Access random rune element of string without using for ... range
(1 answer)
Closed 4 years ago.
package main
import (
"fmt"
_ "math"
"unsafe"
)
func main() {
var s1 = "한글"
fmt.Println(s1[0]);
}
I want to extract string element like s1[0]. But I didn't get the correct element. Just returned number. I don't know the meaning of the number. I think there'is a library which is unicode/utf8.
But I don't know how I get the correct value from the element using this.
I want to extract '한' this word.
Can you help me how I can convert?
package main
import (
"fmt"
)
func main() {
var s1 = "한글"
var s2 = []rune(s1)
fmt.Println(string(s2[0]))
}

How to expand variables with fmt.Println()

I can't expand variables with fmt.Println().
package main
import "fmt"
func main(){
old := 20
fmt.Println("I'm %g years old.",old)
}
result =>
I'm %g years old.
20
Use Printf not Println. Use %d for old which is type int. Add a newline.
For example,
package main
import "fmt"
func main() {
old := 20
fmt.Printf("I'm %d years old.\n", old)
}
Output:
I'm 20 years old.
As the documentation for fmt.Println states, this function does not support format specifiers. Use fmt.Printf instead.

Generating Random Timestamps in Go

I'd like to generate a random timestamp within the last relative 3 years and have it be printed out with this format: %d/%b/%Y:%H:%M:%S %z
Here is what I have right now:
package main
import (
"strconv"
"time"
"math/rand"
"fmt"
)
func randomTimestamp() time.Time {
randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000
randomNow, err := time.Parse("10/Oct/2000:13:55:36 -0700", strconv.FormatInt(randomTime, 10))
if err != nil {
panic(err)
}
return randomNow
}
func main() {
fmt.Println(randomTimestamp().String())
}
This always throws: panic: parsing time "...": month out of range. How can I generate a random timestamp for a given range, then convert it to the string format I want with the standard library?
Don't use time.Parse. You have a Unix time, not a time string. Use the Unix() method instead. https://golang.org/pkg/time/#Unix. You can also choose a minimum time value, say 1/1/1900 and add a random Duration of seconds to the time using the Add method on Time and passing a Duration you made with the Ticks() method. https://golang.org/pkg/time/#Duration
Here's a Go Playground link. Just remember that the Go Playground doesn't support actual randomness. https://play.golang.org/p/qYTpnbml_N
package main
import (
"time"
"math/rand"
"fmt"
)
func randomTimestamp() time.Time {
randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000
randomNow := time.Unix(randomTime, 0)
return randomNow
}
func main() {
fmt.Println(randomTimestamp().String())
}

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