datetime.go 9.9 KB

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