publish time-formatting-parsing

This commit is contained in:
Mark McGranaghan 2012-11-01 15:26:20 -07:00
parent 2a17561156
commit 5110cee76a
5 changed files with 67 additions and 1 deletions

View File

@ -47,7 +47,7 @@ Regular Expressions
JSON
Time
Epoch
# Time Parsing / Formatting
Time Formatting / Parsing
Random Numbers
Number Parsing
URL Parsing

View File

@ -5,3 +5,6 @@ $ go run epoch.go
1351700038292387000
2012-10-31 16:13:58 +0000 UTC
2012-10-31 16:13:58.292387 +0000 UTC
# Next we'll look at another time-related task: time
# parsing and formatting.

View File

@ -0,0 +1,52 @@
// Go supports time formatting and parsing via
// pattern-based layouts.
package main
import "fmt"
import "time"
func main() {
p := fmt.Println
// Here's a basic example of formatting a time
// according to RFC3339.
t := time.Now()
p(t.Format("2006-01-02T15:04:05Z07:00"))
// `Format` uses an example-based layout approach; it
// takes a formatted version of the reference time
// `Mon Jan 2 15:04:05 MST 2006` to determine the
// general pattern with which to format the given
// time. Here are a few more examples of time
// formatting.
p(t.Format("4:05PM"))
p(t.Format("Mon Jan _2 15:04:05 2006"))
p(t.Format("2006-01-02T15:04:05.999999-07:00"))
// For purely numeric representations you can also
// use standard string formatting with the extracted
// components of the time value.
fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
// Time parsing uses the same example-based approach
// as `Format`ing. These examples parse times rendered
// with some of the layouts used above.
t1, e := time.Parse(
"2006-01-02T15:04:05.999999999-07:00",
"2012-11-01T22:08:41.117442+00:00")
p(t1)
t2, e := time.Parse(
"4:05PM",
"8:41PM")
p(t2)
// `Parse` will return an error on malformed input
// explaining the parsing problem.
_, e = time.Parse(
"Mon Jan _2 15:04:05 2006",
"8:41PM")
p(e)
}

View File

@ -0,0 +1,9 @@
$ go run time-formatting-parsing.go
2012-11-01T15:17:41-07:00
17:41PM
Thu Nov 1 15:17:41 2012
2012-11-01T15:17:41.256589-07:00
2012-11-01T15:17:41-00:00
0001-01-01 00:00:00 +0000 UTC
0000-01-01 12:08:41 +0000 UTC
parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": ...

View File

@ -129,6 +129,7 @@ func debug(msg string) {
var docsPat = regexp.MustCompile("^\\s*(\\/\\/|#)\\s")
var todoPat = regexp.MustCompile("\\/\\/ todo: ")
var dashPat = regexp.MustCompile("\\-+")
type Seg struct {
Docs, DocsRendered string
@ -213,6 +214,7 @@ func parseExamples() []*Example {
exampleId = strings.Replace(exampleId, " ", "-", -1)
exampleId = strings.Replace(exampleId, "/", "-", -1)
exampleId = strings.Replace(exampleId, "'", "", -1)
exampleId = dashPat.ReplaceAllString(exampleId, "-")
example.Id = exampleId
example.Segs = make([][]*Seg, 0)
sourcePaths := mustGlob("examples/" + exampleId + "/*")