datetime.go 9.6 KB

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