| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package tai64 |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"strconv" |
| 12 |
"time" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
const epochTai64 = (2 << 61) + 10 |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
func GetOffsetUnix(utime int64) int64 { |
| 23 |
|
| 24 |
offset := int64(10) |
| 25 |
|
| 26 |
for i := tia64nSize - 1; i >= 0; i-- { |
| 27 |
if utime < tia64nDifferences[i].utime { |
| 28 |
continue |
| 29 |
} else { |
| 30 |
offset = tia64nDifferences[i].offset |
| 31 |
break |
| 32 |
} |
| 33 |
} |
| 34 |
return offset |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
func GetOffsetTime(t time.Time) int64 { |
| 40 |
return GetOffsetUnix(t.UTC().Unix()) |
| 41 |
} |
| 42 |
|
| 43 |
func getInvOffsetTai64(ttime int64) int64 { |
| 44 |
|
| 45 |
offset := int64(10) |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
for i := tia64nSize - 1; i >= 0; i-- { |
| 50 |
t := tia64nDifferences[i] |
| 51 |
if ttime < (t.ttime) { |
| 52 |
continue |
| 53 |
} else { |
| 54 |
offset = t.offset |
| 55 |
break |
| 56 |
} |
| 57 |
} |
| 58 |
return offset |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
func FormatNano(t time.Time) string { |
| 64 |
t = t.UTC() |
| 65 |
u := t.Unix() |
| 66 |
|
| 67 |
if u < 0 { |
| 68 |
return fmt.Sprintf("@%016x%08x", epochTai64+u, t.Nanosecond()) |
| 69 |
} |
| 70 |
return fmt.Sprintf("@4%015x%08x", u+GetOffsetUnix(u), t.Nanosecond()) |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
func Format(t time.Time) string { |
| 76 |
u := t.UTC().Unix() |
| 77 |
|
| 78 |
if u < 0 { |
| 79 |
return fmt.Sprintf("@%016x", epochTai64+u) |
| 80 |
} |
| 81 |
return fmt.Sprintf("@4%015x", u+GetOffsetUnix(u)) |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
func Parse(s string) (time.Time, error) { |
| 87 |
var tseconds, nanoseconds int64 |
| 88 |
if s[0] == '@' { |
| 89 |
s = s[1:] |
| 90 |
} |
| 91 |
|
| 92 |
if len(s) < 16 { |
| 93 |
return time.Time{}, fmt.Errorf("invalid tai64 time string") |
| 94 |
} |
| 95 |
|
| 96 |
i, err := strconv.ParseInt(s[0:16], 16, 64) |
| 97 |
if err != nil { |
| 98 |
return time.Time{}, err |
| 99 |
} |
| 100 |
tseconds = i |
| 101 |
s = s[16:] |
| 102 |
|
| 103 |
|
| 104 |
slen := len(s) |
| 105 |
if slen == 8 || slen == 16 { |
| 106 |
|
| 107 |
|
| 108 |
i, err := strconv.ParseInt(s[:8], 16, 64) |
| 109 |
if err != nil { |
| 110 |
return time.Time{}, err |
| 111 |
} |
| 112 |
nanoseconds = i |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
if tseconds >= epochTai64 { |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
offset := getInvOffsetTai64(tseconds) |
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
unix := tseconds - epochTai64 - (offset - 10) |
| 127 |
|
| 128 |
t := time.Unix(unix, nanoseconds).UTC() |
| 129 |
return t, nil |
| 130 |
} |
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
unix := -(epochTai64 - tseconds) |
| 135 |
t := time.Unix(unix, nanoseconds).UTC() |
| 136 |
return t, nil |
| 137 |
} |