Skip to content

Commit d7b482b

Browse files
authored
Merge pull request #811 from devlights/add-parse-duration-example
2 parents 3fdcc93 + 5a1bab3 commit d7b482b

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

examples/basic/times/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,4 @@
2828
| time_daysinmonth.go | time_daysinmonth | 月の日数を求めるサンプルです |
2929
| time_sleep.go | time_sleep | time.Sleep() のサンプルです。 |
3030
| time_cancellable_sleep.go | time_cancellable_sleep | キャンセル可能なスリープ処理のサンプルです。 |
31+
| time_parseDuration.go | time_parse_duration | time.ParseDuration() のサンプルです |

examples/basic/times/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
3838
m["time_daysinmonth"] = DaysInMonth
3939
m["time_sleep"] = Sleep
4040
m["time_cancellable_sleep"] = CancellableSleep
41+
m["time_parse_duration"] = ParseDuration
4142
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package times
2+
3+
import (
4+
"time"
5+
6+
"github.com/devlights/gomy/output"
7+
)
8+
9+
// ParseDuration は、time.ParseDuration() のサンプルです.
10+
//
11+
// > ParseDuration parses a duration string.
12+
// A duration string is a possibly signed sequence of decimal numbers,
13+
// each with optional fraction and a unit suffix,
14+
// such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
15+
//
16+
// > ParseDuration は継続時間文字列を解析する。
17+
// 継続時間文字列は、符号付きの10進数列の可能性があり、
18+
// それぞれオプションの分数と "300ms"、"-1.5h"、"2h45m" のような単位の接尾辞があります。
19+
// 有効な時間単位は、"ns"、"us"(または "µs")、"ms"、"s"、"m"、"h "である。
20+
//
21+
// # REFERENCES
22+
// - https://pkg.go.dev/time@go1.22.3#ParseDuration
23+
func ParseDuration() error {
24+
var (
25+
items = []string{
26+
"500ms",
27+
"5s",
28+
"5m",
29+
"5h",
30+
"1h2m3s444ms",
31+
"1h2m3s444ms555us666ns", // ナノ秒まで指定
32+
"1h2m3s4d", // 不正な接尾辞
33+
"1h2m3h4s5h", // 同じ時間単位のものは合計される
34+
"1h2m3h4s5h500ms500ms", // 同じ時間単位のものは合計される
35+
"-1h2m3h4s5h", // 先頭に - を付与すると負の値に出来る
36+
}
37+
)
38+
39+
for _, item := range items {
40+
var (
41+
d time.Duration
42+
err error
43+
)
44+
45+
d, err = time.ParseDuration(item)
46+
if err != nil {
47+
output.Stdoutl("[error]", err)
48+
continue
49+
}
50+
51+
output.Stdoutl("[Duration]", d)
52+
}
53+
54+
return nil
55+
}

0 commit comments

Comments
 (0)