From 67cfd86cf51bbc472a2d46354a337c108f82f104 Mon Sep 17 00:00:00 2001 From: Ge Song Date: Tue, 28 Mar 2023 14:37:41 +0800 Subject: [PATCH] add timehelper; --- timehelper/go.mod | 3 +++ timehelper/time.go | 8 ++++++++ timehelper/time_test.go | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 timehelper/go.mod create mode 100644 timehelper/time.go create mode 100644 timehelper/time_test.go diff --git a/timehelper/go.mod b/timehelper/go.mod new file mode 100644 index 0000000..fa66582 --- /dev/null +++ b/timehelper/go.mod @@ -0,0 +1,3 @@ +module git.blauwelle.com/go/crate/timehelper + +go 1.20 diff --git a/timehelper/time.go b/timehelper/time.go new file mode 100644 index 0000000..b1419b3 --- /dev/null +++ b/timehelper/time.go @@ -0,0 +1,8 @@ +package timehelper + +import "time" + +// SetupCST 把本地时区固定到CST +func SetupCST() { + time.Local = time.FixedZone("CST", 8*3600) +} diff --git a/timehelper/time_test.go b/timehelper/time_test.go new file mode 100644 index 0000000..a70c65c --- /dev/null +++ b/timehelper/time_test.go @@ -0,0 +1,34 @@ +package timehelper_test + +import ( + "fmt" + "time" +) + +// Javascript 只能精确到毫秒: +// new Date('2023-01-15T15:16:17.123456789+08:00').toISOString() +// Output: '2023-01-15T07:16:17.123Z' +func ExampleRFC3339Nano() { + t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+08:00") + fmt.Println(t.Format(time.RFC3339Nano)) + // Output: 2023-01-15T15:16:17.123456789+08:00 +} + +func ExampleRFC3339Nano2Sec() { + t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+08:00") + fmt.Println(t.Format(time.RFC3339)) + // Output: 2023-01-15T15:16:17+08:00 +} + +// 使用 RFC3339 没有丢失纳秒精度 +func ExampleRFC3339Sec2Nano() { + t, _ := time.Parse(time.RFC3339, "2023-01-15T15:16:17.123456789+08:00") + fmt.Println(t.Format(time.RFC3339Nano)) + // Output: 2023-01-15T15:16:17.123456789+08:00 +} + +func ExampleRFC3339NanoOtherZone() { + t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+09:00") + fmt.Println(t.Format(time.RFC3339Nano)) + // Output: 2023-01-15T15:16:17.123456789+09:00 +}