time.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. tm := t.T()
  166. return tm.Second() == 0 && tm.Nanosecond() == 0
  167. }
  168. // 获取年、月、日
  169. func (t Time) Date() (year int, month time.Month, day int) {
  170. return t.T().Date()
  171. }
  172. // 获取年
  173. func (t Time) Year() int {
  174. return t.T().Year()
  175. }
  176. // 获取月
  177. func (t Time) Month() time.Month {
  178. return t.T().Month()
  179. }
  180. // 获取日
  181. func (t Time) Day() int {
  182. return t.T().Day()
  183. }
  184. // 获取星期几
  185. func (t Time) Weekday() time.Weekday {
  186. return t.T().Weekday()
  187. }
  188. // 获取年、第几周
  189. func (t Time) ISOWeek() (year, week int) {
  190. return t.T().ISOWeek()
  191. }
  192. // 获取时、分、秒
  193. func (t Time) Clock() (hour, min, sec int) {
  194. return t.T().Clock()
  195. }
  196. // 获取小时
  197. func (t Time) Hour() int {
  198. return t.T().Hour()
  199. }
  200. // 获取分钟
  201. func (t Time) Minute() int {
  202. return t.T().Minute()
  203. }
  204. // 获取秒
  205. func (t Time) Second() int {
  206. return t.T().Second()
  207. }
  208. // 获取毫秒
  209. func (t Time) Millisecond() int {
  210. return int(time.Duration(t.T().Nanosecond()) / time.Millisecond)
  211. }
  212. // 获取微秒
  213. func (t Time) Microsecond() int {
  214. return int(time.Duration(t.T().Nanosecond()) / time.Microsecond)
  215. }
  216. // 获取纳秒
  217. func (t Time) Nanosecond() int {
  218. return t.T().Nanosecond()
  219. }
  220. // 获取是一年中第几天
  221. func (t Time) YearDay() int {
  222. return t.T().YearDay()
  223. }
  224. // 获取该时间 - 参数时间 的时间差
  225. func (t Time) Sub(u Time) time.Duration {
  226. return t.T().Sub(u.T())
  227. }
  228. // 加一个时间差
  229. func (t Time) Add(d time.Duration) Datetime {
  230. return Datetime(t.T().Add(d))
  231. }
  232. // 加年、月、日
  233. func (t Time) AddDate(years int, months int, days int) Datetime {
  234. return Datetime(t.T().AddDate(years, months, days))
  235. }
  236. // 加时、分、秒
  237. func (t Time) AddTime(hours int, minutes int, seconds int) Datetime {
  238. d := time.Duration(hours)*time.Hour + time.Duration(minutes)*time.Minute + time.Duration(seconds)*time.Second
  239. return t.Add(d)
  240. }
  241. // 加年
  242. func (t Time) AddYears(years int) Datetime {
  243. return t.AddDate(years, 0, 0)
  244. }
  245. // 加月
  246. func (t Time) AddMonths(months int) Datetime {
  247. return t.AddDate(0, months, 0)
  248. }
  249. // 加日
  250. func (t Time) AddDays(days int) Datetime {
  251. return t.AddDate(0, 0, days)
  252. }
  253. // 加小时
  254. func (t Time) AddHours(hours int) Datetime {
  255. d := time.Duration(hours) * time.Hour
  256. return t.Add(d)
  257. }
  258. // 加分钟
  259. func (t Time) AddMinutes(minutes int) Datetime {
  260. d := time.Duration(minutes) * time.Minute
  261. return t.Add(d)
  262. }
  263. // 加秒
  264. func (t Time) AddSeconds(seconds int) Datetime {
  265. d := time.Duration(seconds) * time.Second
  266. return t.Add(d)
  267. }
  268. // 加纳秒
  269. func (t Time) AddNanoseconds(nanoseconds int) Datetime {
  270. d := time.Duration(nanoseconds) * time.Nanosecond
  271. return t.Add(d)
  272. }
  273. // 指定时间
  274. func (t Time) Of(year int, month time.Month, day int, hour int, minute int, second int, nanosecond int) Datetime {
  275. return Datetime(time.Date(year, month, day, hour, minute, second, nanosecond, t.Location()))
  276. }
  277. // 指定年、月、日
  278. func (t Time) OfDate(year int, month time.Month, day int) Datetime {
  279. hour, minute, second := t.Clock()
  280. return t.Of(year, month, day, hour, minute, second, t.Nanosecond())
  281. }
  282. // 指定时、分、秒
  283. func (t Time) OfTime(hour int, minute int, second int) Time {
  284. year, month, day := t.Date()
  285. return Time(t.Of(year, month, day, hour, minute, second, t.Nanosecond()))
  286. }
  287. // 指定年
  288. func (t Time) OfYear(year int) Datetime {
  289. return t.OfDate(year, t.Month(), t.Day())
  290. }
  291. // 指定月
  292. func (t Time) OfMonth(month time.Month) Datetime {
  293. return t.OfDate(t.Year(), month, t.Day())
  294. }
  295. // 指定日
  296. func (t Time) OfDay(day int) Datetime {
  297. return t.OfDate(t.Year(), t.Month(), day)
  298. }
  299. // 指定小时
  300. func (t Time) OfHour(hour int) Time {
  301. return t.OfTime(hour, t.Minute(), t.Second())
  302. }
  303. // 指定分钟
  304. func (t Time) OfMinute(minute int) Time {
  305. return t.OfTime(t.Hour(), minute, t.Second())
  306. }
  307. // 指定秒
  308. func (t Time) OfSecond(second int) Time {
  309. return t.OfTime(t.Hour(), t.Minute(), second)
  310. }
  311. // 指定纳秒
  312. func (t Time) OfNanosecond(nanosecond int) Time {
  313. year, month, day := t.Date()
  314. hour, minute, second := t.Clock()
  315. return Time(t.Of(year, month, day, hour, minute, second, nanosecond))
  316. }
  317. // 转UTC时间
  318. func (t Time) UTC() Datetime {
  319. return Datetime(t.T().UTC())
  320. }
  321. // 转本地时间
  322. func (t Time) Local() Datetime {
  323. return Datetime(t.T().Local())
  324. }
  325. // 转指定时区时间
  326. func (t Time) In(loc *time.Location) Datetime {
  327. return Datetime(t.T().In(loc))
  328. }
  329. // 获取时区
  330. func (t Time) Location() *time.Location {
  331. return t.T().Location()
  332. }
  333. // 获取时区
  334. func (t Time) Zone() (name string, offset int) {
  335. return t.T().Zone()
  336. }
  337. // 获取UTC时间戳
  338. func (t Time) Unix() int64 {
  339. return t.T().Unix()
  340. }
  341. // 获取UTC纳秒数
  342. func (t Time) UnixNano() int64 {
  343. return t.T().Unix()
  344. }
  345. // 从目标时间开始到现在的时间差
  346. func SinceTime(t Time) time.Duration {
  347. return CurrentTime().Sub(t)
  348. }
  349. // 现在到目标时间的时间差
  350. func UntilTime(t Time) time.Duration {
  351. return t.Sub(CurrentTime())
  352. }