time.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package date
  2. import (
  3. "database/sql/driver"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "github.com/vmihailenco/msgpack"
  8. "strings"
  9. "time"
  10. )
  11. type Time time.Time
  12. const NormalTimeFormat = "15:04:05"
  13. func init() {
  14. msgpack.RegisterExt(2, (*Time)(nil))
  15. }
  16. func (t Time) MarshalJSON() ([]byte, error) {
  17. if y := t.Year(); y < 0 || y >= 10000 {
  18. return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
  19. }
  20. if t.IsZero() {
  21. b := []byte(`""`)
  22. return b, nil
  23. }
  24. b := make([]byte, 0, len(NormalTimeFormat)+2)
  25. b = append(b, '"')
  26. b = t.AppendFormat(b, NormalTimeFormat)
  27. b = append(b, '"')
  28. return b, nil
  29. }
  30. func (t *Time) UnmarshalJSON(value []byte) error {
  31. var v = strings.TrimSpace(strings.Trim(string(value), "\""))
  32. if v == "" {
  33. return nil
  34. }
  35. tm, err := time.ParseInLocation(NormalTimeFormat, v, time.Local)
  36. if err != nil {
  37. return err
  38. }
  39. *t = Time(Time(tm).OfDate(1, time.January, 1))
  40. return nil
  41. }
  42. func (t *Time) MarshalMsgpack() ([]byte, error) {
  43. b := make([]byte, 8)
  44. binary.BigEndian.PutUint32(b, uint32(t.Unix()))
  45. binary.BigEndian.PutUint32(b[4:], uint32(t.Nanosecond()))
  46. return b, nil
  47. }
  48. func (t *Time) UnmarshalMsgpack(b []byte) error {
  49. if len(b) != 8 {
  50. return fmt.Errorf("invalid data length: got %d, wanted 8", len(b))
  51. }
  52. sec := binary.BigEndian.Uint32(b)
  53. usec := binary.BigEndian.Uint32(b[4:])
  54. *t = Time(time.Unix(int64(sec), int64(usec)))
  55. return nil
  56. }
  57. func TimeRegisterExt() {
  58. t := Time(time.Unix(123456789, 123))
  59. b, err := msgpack.Marshal(&t)
  60. if err != nil {
  61. panic(err)
  62. }
  63. var v interface{}
  64. err = msgpack.Unmarshal(b, &v)
  65. if err != nil {
  66. panic(err)
  67. }
  68. fmt.Println(v.(*Time).UTC())
  69. tm := &Time{}
  70. err = msgpack.Unmarshal(b, tm)
  71. if err != nil {
  72. panic(err)
  73. }
  74. fmt.Println(tm.UTC())
  75. // Output: 1973-11-29 21:33:09.000000123 +0000 UTC
  76. // 1973-11-29 21:33:09.000000123 +0000 UTC
  77. }
  78. func (t Time) MarshalText() ([]byte, error) {
  79. if y := t.Year(); y < 0 || y >= 10000 {
  80. return nil, errors.New("Time.MarshalText: year outside of range [0,9999]")
  81. }
  82. b := make([]byte, 0, len(NormalTimeFormat))
  83. return t.AppendFormat(b, NormalTimeFormat), nil
  84. }
  85. func (t *Time) UnmarshalText(data []byte) error {
  86. *t = t.FromString(string(data))
  87. return nil
  88. }
  89. func (t Time) FromString(str string) Time {
  90. return ParseTime(str)
  91. }
  92. func ParseTime(str string) Time {
  93. str = dateStrFormat(str)
  94. return ParseTimeFormat(str, NormalTimeFormat)
  95. }
  96. func ParseTimeFormat(str string, format string) Time {
  97. str = strings.TrimSpace(str)
  98. tm, err := time.ParseInLocation(format, str, time.Local)
  99. if nil != err {
  100. return Unix(0, 0).ToTime()
  101. }
  102. return Time(Time(tm).OfDate(1, time.January, 1))
  103. }
  104. func (t Time) String() string {
  105. return t.Format(NormalTimeFormat)
  106. }
  107. func (t Time) Value() (driver.Value, error) {
  108. if t.IsZero() {
  109. return nil, nil
  110. }
  111. return t.Format(NormalTimeFormat), nil
  112. }
  113. func (t *Time) Scan(value interface{}) error {
  114. if value == nil {
  115. return nil
  116. }
  117. *t = Time(value.(time.Time))
  118. return nil
  119. }
  120. func (t Time) Format(layout string) string {
  121. layout = strings.TrimSpace(layout)
  122. return t.T().Format(layout)
  123. }
  124. func (t Time) AppendFormat(b []byte, layout string) []byte {
  125. return t.T().AppendFormat(b, layout)
  126. }
  127. // 当前时间
  128. func CurrentTime() Time {
  129. return Time(Time(time.Now()).OfDate(1, time.January, 1))
  130. }
  131. // 构造date.Time
  132. func NewTime(hour, min, sec, nsec int, loc *time.Location) Time {
  133. return Time(time.Date(1, time.January, 1, hour, min, sec, nsec, loc))
  134. }
  135. // 转date.Datetime
  136. func (t Time) ToDatetime() Datetime {
  137. return Datetime(t)
  138. }
  139. // 转date.Date
  140. func (t Time) ToDate() Date {
  141. return Date(t)
  142. }
  143. // 转date.Time
  144. func AsTime(tm time.Time) Time {
  145. return Time(Time(tm).OfDate(1, time.January, 1))
  146. }
  147. // 转time.Time
  148. func (t Time) T() time.Time {
  149. return time.Time(t)
  150. }
  151. // 是否晚于
  152. func (t Time) After(u Time) bool {
  153. return t.T().After(u.T())
  154. }
  155. // 是否早于
  156. func (t Time) Before(u Time) bool {
  157. return t.T().Before(u.T())
  158. }
  159. // 是否等于
  160. func (t Time) Equal(u Time) bool {
  161. return t.T().Equal(u.T())
  162. }
  163. // 是否零值
  164. func (t Time) IsZero() bool {
  165. return t.T().IsZero()
  166. }
  167. // 获取年、月、日
  168. func (t Time) Date() (year int, month time.Month, day int) {
  169. return t.T().Date()
  170. }
  171. // 获取年
  172. func (t Time) Year() int {
  173. return t.T().Year()
  174. }
  175. // 获取月
  176. func (t Time) Month() time.Month {
  177. return t.T().Month()
  178. }
  179. // 获取日
  180. func (t Time) Day() int {
  181. return t.T().Day()
  182. }
  183. // 获取星期几
  184. func (t Time) Weekday() time.Weekday {
  185. return t.T().Weekday()
  186. }
  187. // 获取年、第几周
  188. func (t Time) ISOWeek() (year, week int) {
  189. return t.T().ISOWeek()
  190. }
  191. // 获取时、分、秒
  192. func (t Time) Clock() (hour, min, sec int) {
  193. return t.T().Clock()
  194. }
  195. // 获取小时
  196. func (t Time) Hour() int {
  197. return t.T().Hour()
  198. }
  199. // 获取分钟
  200. func (t Time) Minute() int {
  201. return t.T().Minute()
  202. }
  203. // 获取秒
  204. func (t Time) Second() int {
  205. return t.T().Second()
  206. }
  207. // 获取毫秒
  208. func (t Time) Millisecond() int {
  209. return int(time.Duration(t.T().Nanosecond()) / time.Millisecond)
  210. }
  211. // 获取微秒
  212. func (t Time) Microsecond() int {
  213. return int(time.Duration(t.T().Nanosecond()) / time.Microsecond)
  214. }
  215. // 获取纳秒
  216. func (t Time) Nanosecond() int {
  217. return t.T().Nanosecond()
  218. }
  219. // 获取是一年中第几天
  220. func (t Time) YearDay() int {
  221. return t.T().YearDay()
  222. }
  223. // 获取该时间 - 参数时间 的时间差
  224. func (t Time) Sub(u Time) time.Duration {
  225. return t.T().Sub(u.T())
  226. }
  227. // 加一个时间差
  228. func (t Time) Add(d time.Duration) Datetime {
  229. return Datetime(t.T().Add(d))
  230. }
  231. // 加年、月、日
  232. func (t Time) AddDate(years int, months int, days int) Datetime {
  233. return Datetime(t.T().AddDate(years, months, days))
  234. }
  235. // 加时、分、秒
  236. func (t Time) AddTime(hours int, minutes int, seconds int) Datetime {
  237. d := time.Duration(hours)*time.Hour + time.Duration(minutes)*time.Minute + time.Duration(seconds)*time.Second
  238. return t.Add(d)
  239. }
  240. // 加年
  241. func (t Time) AddYears(years int) Datetime {
  242. return t.AddDate(years, 0, 0)
  243. }
  244. // 加月
  245. func (t Time) AddMonths(months int) Datetime {
  246. return t.AddDate(0, months, 0)
  247. }
  248. // 加日
  249. func (t Time) AddDays(days int) Datetime {
  250. return t.AddDate(0, 0, days)
  251. }
  252. // 加小时
  253. func (t Time) AddHours(hours int) Datetime {
  254. d := time.Duration(hours) * time.Hour
  255. return t.Add(d)
  256. }
  257. // 加分钟
  258. func (t Time) AddMinutes(minutes int) Datetime {
  259. d := time.Duration(minutes) * time.Minute
  260. return t.Add(d)
  261. }
  262. // 加秒
  263. func (t Time) AddSeconds(seconds int) Datetime {
  264. d := time.Duration(seconds) * time.Second
  265. return t.Add(d)
  266. }
  267. // 加纳秒
  268. func (t Time) AddNanoseconds(nanoseconds int) Datetime {
  269. d := time.Duration(nanoseconds) * time.Nanosecond
  270. return t.Add(d)
  271. }
  272. // 指定时间
  273. func (t Time) Of(year int, month time.Month, day int, hour int, minute int, second int, nanosecond int) Datetime {
  274. return Datetime(time.Date(year, month, day, hour, minute, second, nanosecond, t.Location()))
  275. }
  276. // 指定年、月、日
  277. func (t Time) OfDate(year int, month time.Month, day int) Datetime {
  278. hour, minute, second := t.Clock()
  279. return t.Of(year, month, day, hour, minute, second, t.Nanosecond())
  280. }
  281. // 指定时、分、秒
  282. func (t Time) OfTime(hour int, minute int, second int) Time {
  283. year, month, day := t.Date()
  284. return Time(t.Of(year, month, day, hour, minute, second, t.Nanosecond()))
  285. }
  286. // 指定年
  287. func (t Time) OfYear(year int) Datetime {
  288. return t.OfDate(year, t.Month(), t.Day())
  289. }
  290. // 指定月
  291. func (t Time) OfMonth(month time.Month) Datetime {
  292. return t.OfDate(t.Year(), month, t.Day())
  293. }
  294. // 指定日
  295. func (t Time) OfDay(day int) Datetime {
  296. return t.OfDate(t.Year(), t.Month(), day)
  297. }
  298. // 指定小时
  299. func (t Time) OfHour(hour int) Time {
  300. return t.OfTime(hour, t.Minute(), t.Second())
  301. }
  302. // 指定分钟
  303. func (t Time) OfMinute(minute int) Time {
  304. return t.OfTime(t.Hour(), minute, t.Second())
  305. }
  306. // 指定秒
  307. func (t Time) OfSecond(second int) Time {
  308. return t.OfTime(t.Hour(), t.Minute(), second)
  309. }
  310. // 指定纳秒
  311. func (t Time) OfNanosecond(nanosecond int) Time {
  312. year, month, day := t.Date()
  313. hour, minute, second := t.Clock()
  314. return Time(t.Of(year, month, day, hour, minute, second, nanosecond))
  315. }
  316. // 转UTC时间
  317. func (t Time) UTC() Datetime {
  318. return Datetime(t.T().UTC())
  319. }
  320. // 转本地时间
  321. func (t Time) Local() Datetime {
  322. return Datetime(t.T().Local())
  323. }
  324. // 转指定时区时间
  325. func (t Time) In(loc *time.Location) Datetime {
  326. return Datetime(t.T().In(loc))
  327. }
  328. // 获取时区
  329. func (t Time) Location() *time.Location {
  330. return t.T().Location()
  331. }
  332. // 获取时区
  333. func (t Time) Zone() (name string, offset int) {
  334. return t.T().Zone()
  335. }
  336. // 获取UTC时间戳
  337. func (t Time) Unix() int64 {
  338. return t.T().Unix()
  339. }
  340. // 获取UTC纳秒数
  341. func (t Time) UnixNano() int64 {
  342. return t.T().Unix()
  343. }
  344. // 从目标时间开始到现在的时间差
  345. func SinceTime(t Time) time.Duration {
  346. return CurrentTime().Sub(t)
  347. }
  348. // 现在到目标时间的时间差
  349. func UntilTime(t Time) time.Duration {
  350. return t.Sub(CurrentTime())
  351. }