Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing 0 for single-digit hours with golang time package

I'm trying to format a series a date such as:

  • March 12th, 2013, 3pm looks like : 2013-03-12-15.txt
  • March 12th, 2013, 4am looks like : 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 !

like image 490
mazieres Avatar asked May 02 '14 12:05

mazieres


People also ask

How do you parse time in go?

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.

What does time duration do in Golang?

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.

What does time now return Golang?

Return Value: It returns the current local time.

Which is a valid GO time format literal?

Golang Time Format YYYY-MM-DD.


1 Answers

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)
like image 174
Sebastian Avatar answered Sep 19 '22 02:09

Sebastian