Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
55 lines (45 sloc) 988 Bytes

解析日期的代码示例

本节的代码parseDate.go,分两部分讲解。

第一部分:

package main

import (
   "fmt"
   "os"
   "path/filepath"
   "time"
)

func main() {
   var myDate string

   if len(os.Args) != 2 {
      fmt.Printf("Usage: %s date\n",
         filepath.Base(os.Args[0]))
      os.Exit(0)
   }

   myDate = os.Args[1]

第二部分:

d,err := time.Parse("02 January 2006",myDate)
   if err == nil {
      fmt.Println("Full",d)
      fmt.Println("Time", d.Day(), d.Month(), d.Year())
   } else {
      fmt.Println(err)
   }
}

如果你想要在月份和年之间加入"-",只需要将格式“02 January 2006“改成“02 January-2006”即可。

执行parseDate.go你将得到下面的输出:

$ go run parseDate.go

usage: parseDate string

$ go run parseDate.go "12 January 2019"

Full 2019-01-12 00:00:00 +0000 UTC Time 12 January 2019

You can’t perform that action at this time.