time.go 8.4 KB

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