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