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 +}