- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
这是我的程序
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)
}
输出是
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/
我是一名优秀的程序员,十分优秀!