datetime.go 9.8 KB

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