Go - Formatting time

发布时间 2023-10-06 12:59:49作者: ZhangZhihuiAAA

 

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:

Sat  Oct  23  15:05:37  +08  2021
22  Oct  23  15:05  +08
Saturday,  23 - Oct - 21  15:05:37  +08
Sat,  23  Oct  2021  15:05:37  +08
2021 - 10 - 23T15:05:37+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:

Oct  23  15:10:53
Oct  23  15:10:53.899
Oct  23  15:10:53.899873
Oct  23  15:10:53.899873000

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, and the time zone must be 7.