diff --git a/examples/basic/times/README.md b/examples/basic/times/README.md index 7176ac11..c9061a9a 100644 --- a/examples/basic/times/README.md +++ b/examples/basic/times/README.md @@ -28,3 +28,4 @@ | time_daysinmonth.go | time_daysinmonth | 月の日数を求めるサンプルです | | time_sleep.go | time_sleep | time.Sleep() のサンプルです。 | | time_cancellable_sleep.go | time_cancellable_sleep | キャンセル可能なスリープ処理のサンプルです。 | +| time_parseDuration.go | time_parse_duration | time.ParseDuration() のサンプルです | diff --git a/examples/basic/times/examples.go b/examples/basic/times/examples.go index 7aa6b7e0..c3664c3a 100644 --- a/examples/basic/times/examples.go +++ b/examples/basic/times/examples.go @@ -38,4 +38,5 @@ func (r *register) Regist(m mapping.ExampleMapping) { m["time_daysinmonth"] = DaysInMonth m["time_sleep"] = Sleep m["time_cancellable_sleep"] = CancellableSleep + m["time_parse_duration"] = ParseDuration } diff --git a/examples/basic/times/time_parseDuration.go b/examples/basic/times/time_parseDuration.go new file mode 100644 index 00000000..3e780854 --- /dev/null +++ b/examples/basic/times/time_parseDuration.go @@ -0,0 +1,55 @@ +package times + +import ( + "time" + + "github.com/devlights/gomy/output" +) + +// ParseDuration は、time.ParseDuration() のサンプルです. +// +// > ParseDuration parses a duration string. +// A duration string is a possibly signed sequence of decimal numbers, +// each with optional fraction and a unit suffix, +// such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". +// +// > ParseDuration は継続時間文字列を解析する。 +// 継続時間文字列は、符号付きの10進数列の可能性があり、 +// それぞれオプションの分数と "300ms"、"-1.5h"、"2h45m" のような単位の接尾辞があります。 +// 有効な時間単位は、"ns"、"us"(または "µs")、"ms"、"s"、"m"、"h "である。 +// +// # REFERENCES +// - https://pkg.go.dev/time@go1.22.3#ParseDuration +func ParseDuration() error { + var ( + items = []string{ + "500ms", + "5s", + "5m", + "5h", + "1h2m3s444ms", + "1h2m3s444ms555us666ns", // ナノ秒まで指定 + "1h2m3s4d", // 不正な接尾辞 + "1h2m3h4s5h", // 同じ時間単位のものは合計される + "1h2m3h4s5h500ms500ms", // 同じ時間単位のものは合計される + "-1h2m3h4s5h", // 先頭に - を付与すると負の値に出来る + } + ) + + for _, item := range items { + var ( + d time.Duration + err error + ) + + d, err = time.ParseDuration(item) + if err != nil { + output.Stdoutl("[error]", err) + continue + } + + output.Stdoutl("[Duration]", d) + } + + return nil +}