datetime.go 8.6 KB

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