ZhangZhihui's Blog  

 

func main() {
    t := time.Now()
    fmt.Println(t.Format("3:04PM"))
    fmt.Println(t.Format("Jan 02, 2006"))
}

When you run this you should see something like:

1:45PM
Oct 23, 2021

That’s simple enough. The time package makes it even simpler because it has several layout constants that you can use directly (note those RFCs described earlier):

func main() {
    t := time.Now()
    fmt.Println(t.Format(time.UnixDate))
    fmt.Println(t.Format(time.RFC822))
    fmt.Println(t.Format(time.RFC850))
    fmt.Println(t.Format(time.RFC1123))
    fmt.Println(t.Format(time.RFC3339))
}

Here’s the output:

zzh@ZZHPC:~/zd/MyPrograms/Go/study$ go run main.go
Tue Oct 24 19:22:21 CST 2023
24 Oct 23 19:22 CST
Tuesday, 24-Oct-23 19:22:21 CST
Tue, 24 Oct 2023 19:22:21 CST
2023-10-24T19:22:21+08:00

Besides the RFCs, there are a few other formats including the interestingly named Kitchen layout, which is just 3:04 p.m. Also if you’re interested in doing timestamps, there are a few timestamp layouts as well:

func main() {
    t := time.Now()
    fmt.Println(t.Format(time.Stamp))
    fmt.Println(t.Format(time.StampMilli))
    fmt.Println(t.Format(time.StampMicro))
    fmt.Println(t.Format(time.StampNano))
}

Here’s the output:

zzh@ZZHPC:~/zd/MyPrograms/Go/study$ go run main.go
Oct 24 19:25:23
Oct 24 19:25:23.012
Oct 24 19:25:23.012032
Oct 24 19:25:23.012032287

You might have seen earlier that the layout patterns are like this:

t.Format("3:04PM")

The full layout pattern is a layout by itself — it’s the time.Layout constant:

const Layout = "01/02 03:04:05PM 06 -0700"

As you can see, the numerals are ascending, starting with 1 and ending with 7. Because of a historic error (mentioned in the time package documentation), the date uses the American convention of putting the numerical month before the day. This means 01/02 is January 2 and not 1 February.

The numbers are not arbitrary. Take this code fragment, where you use the format “ 3:09pm ” instead of “ 3:04pm ”:

func main() {
    t := time.Date(2009, time.November, 10, 23, 45, 0, 0, time.UTC)
    fmt.Println(t.Format(time.Kitchen))
    fmt.Println(t.Format("3:04pm")) //  the  correct  layout
    fmt.Println(t.Format("3:09pm")) //  mucking  around
}

This is the output:

11:45pm
11:45pm
11:09pm

You can see that the time is 11:45 p.m., but when you use the layout 3:09 p.m., the hour is displayed correctly while the minute is not. It shows :09, which means it’s considering 09 as the label instead of a layout for minute.

What this means is that the numerals are not just a placeholder for show. The month must be 1, day must be 2, hour must be 3, minute must be 4, second must be 5, year must be 6, the time zone must be -07 following by zero or more 0, and the pm can not be am.

 

posted on 2023-10-06 12:54  ZhangZhihuiAAA  阅读(10)  评论(0编辑  收藏  举报