简体   繁体   中英

How to format this string in Go

Here is my program

package main

import "fmt"
import "time"
import "strconv"
import "strings"

func main() {

    t := time.Date(2016, 10, 30, 14, 0, 0, 0, time.UTC) 


    year, month, day := t.Date()          
    hr := t.Hour()  

    s := []string{strconv.Itoa(year), strconv.Itoa(int(month)), strconv.Itoa(day)}
    date := strings.Join(s, "")

    s = []string{date, strconv.Itoa(hr)}
    date = strings.Join(s, "_")
    fmt.Println(date)       

}

Go Playground

The output is

20161030_14

If I replace

t := time.Date(2016, 10, 30, 14, 0, 0, 0, time.UTC)

with

t := time.Date(2016, 6, 3, 9, 0, 0, 0, time.UTC)

then the output is

201663_9

but I hope it outputs

20160603_09

ie the month, day and hour should all be two-character long with possibly adding 0 in front. How can I do that?

Or if you were me, what would be your program which implements the same thing?

Thanks.

Use the formatting provided by the time package :

https://play.golang.org/p/qIZ58CJqZa

t := time.Date(2016, 6, 3, 9, 0, 0, 0, time.UTC)
fmt.Println(t.Format("20060102_15"))

From the time package documentation on the reference time format string:

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. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.

Within the format string, an underscore _ represents a space that may be replaced by a digit if the following number (a day) has two digits; for compatibility with fixed-width Unix time formats.

A decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. When parsing (only), the input may contain a fractional second field immediately after the seconds field, even if the layout does not signify its presence. In that case a decimal point followed by a maximal series of digits is parsed as a fractional second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM