I'm trying to format a series a date such as:
2013-03-12-15.txt
2013-03-12-4.txt
Using golang and the Time package
package main
import (
"time"
"fmt"
)
const layout = "2006-01-02-15.txt"
func main() {
t := time.Date(2013, time.March, 12, 4, 0, 0, 0, time.UTC)
fmt.Println(t.Format(layout))
}
Which unfortunately add a zero in front of the single-digit hour : 2013-03-12-04.txt
Is there an idiomatic way to reach the desired output, or I must tweak myself something with the String package ?
Thanks in advance for your help !
How to parse datetime in Go. Parse is a function that accepts a string layout and a string value as arguments. Parse parses the value using the provided layout and returns the Time object it represents. It returns an error if the string value specified is not a valid datetime.
Duration has a base type int64. Duration represents the elapsed time between two instants as an int64 nanosecond count”. The maximum possible nanosecond representation is up to 290 years.
Return Value: It returns the current local time.
Golang Time Format YYYY-MM-DD.
In case you need 24-hour format and don't want the leading zero for hour < 10
I only see a custom string format:
date := fmt.Sprintf("%d-%d-%d-%d", t.Year(), t.Month(), t.Day(), t.Hour())
Of course not an idiomatic way to format a date in Go.
Update (thanks for the comment):
t := time.Now()
date := fmt.Sprintf("%s-%d.txt", t.Format("2006-01-02"), t.Hour())
fmt.Println(date)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With