Go ParseDuration()

개요[ | ]

Go ParseDuration()
package main

import (
	"fmt"
	"time"
)

func main() {
	d, _ := time.ParseDuration("3600.01234567890123456789s")

	fmt.Println(d)                               // 1h0m0.012345678s
	fmt.Println(d.Round(time.Millisecond))       // 1h0m0.012s
	fmt.Println(d.Round(10 * time.Millisecond))  // 1h0m0.01s
	fmt.Println(d.Round(100 * time.Millisecond)) // 1h0m0s
}
package main

import (
	"fmt"
	"time"
)

func main() {
	hours, _ := time.ParseDuration("10h")
	complex, _ := time.ParseDuration("1h10m10s")
	micro, _ := time.ParseDuration("1µs")
	// The package also accepts the incorrect but common prefix u for micro.
	micro2, _ := time.ParseDuration("1us")

	fmt.Println(hours)
	fmt.Println(complex)
	fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
	fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
	fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro)
}
// https://github.com/prometheus/common/blob/88f1636b699ae4fb949d292ffb904c205bf542c9/model/time.go#L190
package main

import (
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"time"
)

var durationRE = regexp.MustCompile("^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$")

func ParseDuration(durationStr string) (time.Duration, error) {
	switch durationStr {
	case "0":
		return 0, nil
	case "":
		return 0, errors.New("empty duration string")
	}
	matches := durationRE.FindStringSubmatch(durationStr)
	if matches == nil {
		return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
	}
	var dur time.Duration
	var overflowErr error
	m := func(pos int, mult time.Duration) {
		if matches[pos] == "" {
			return
		}
		n, _ := strconv.Atoi(matches[pos])
		if n > int((1<<63-1)/mult/time.Millisecond) {
			overflowErr = errors.New("duration out of range")
		}
		d := time.Duration(n) * time.Millisecond
		dur += d * mult
		if dur < 0 {
			overflowErr = errors.New("duration out of range")
		}
	}
	m(2, 1000*60*60*24*365) // y
	m(4, 1000*60*60*24*7)   // w
	m(6, 1000*60*60*24)     // d
	m(8, 1000*60*60)        // h
	m(10, 1000*60)          // m
	m(12, 1000)             // s
	m(14, 1)                // ms
	return time.Duration(dur), overflowErr
}

func main() {
	var hours time.Duration
	hours, _ = ParseDuration("10s")
	fmt.Println(hours) // 10s
	hours, _ = ParseDuration("10m")
	fmt.Println(hours) // 10m0s
	hours, _ = ParseDuration("10h")
	fmt.Println(hours) // 10h0m0s
	hours, _ = ParseDuration("10d")
	fmt.Println(hours) // 240h0m0s
	hours, _ = ParseDuration("10w")
	fmt.Println(hours) // 1680h0m0s
	hours, _ = ParseDuration("10y")
	fmt.Println(hours) // 87600h0m0s
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}