doujia7094 2016-07-29 17:32
浏览 159

如何在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

i.e. 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.

  • 写回答

1条回答 默认 最新

  • doupin5667 2016-07-29 17:36
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了