gpt4 book ai didi

string - 如何在 Go 中格式化这个字符串

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:55 26 4
gpt4 key购买 nike

这是我的程序

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

输出是

20161030_14

如果我更换

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

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

那么输出是

201663_9

但我希望它输出

20160603_09

即月、日和小时都应该是两个字符长,并可能在前面添加 0。我怎样才能做到这一点?

或者,如果您是我,您的程序会怎样实现相同的功能?

谢谢。

最佳答案

使用格式 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"))

来自引用时间格式字符串的时间包文档:

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.

关于string - 如何在 Go 中格式化这个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com