gtime.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. // Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gtime provides functionality for measuring and displaying time.
  7. //
  8. // This package should keep much less dependencies with other packages.
  9. package gtime
  10. import (
  11. "fmt"
  12. "github.com/gogf/gf/errors/gerror"
  13. "github.com/gogf/gf/internal/utils"
  14. "os"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/gogf/gf/text/gregex"
  20. )
  21. const (
  22. // Short writes for common usage durations.
  23. D = 24 * time.Hour
  24. H = time.Hour
  25. M = time.Minute
  26. S = time.Second
  27. MS = time.Millisecond
  28. US = time.Microsecond
  29. NS = time.Nanosecond
  30. // Regular expression1(datetime separator supports '-', '/', '.').
  31. // Eg:
  32. // "2017-12-14 04:51:34 +0805 LMT",
  33. // "2017-12-14 04:51:34 +0805 LMT",
  34. // "2006-01-02T15:04:05Z07:00",
  35. // "2014-01-17T01:19:15+08:00",
  36. // "2018-02-09T20:46:17.897Z",
  37. // "2018-02-09 20:46:17.897",
  38. // "2018-02-09T20:46:17Z",
  39. // "2018-02-09 20:46:17",
  40. // "2018/10/31 - 16:38:46"
  41. // "2018-02-09",
  42. // "2018.02.09",
  43. timeRegexPattern1 = `(\d{4}[-/\.]\d{2}[-/\.]\d{2})[:\sT-]*(\d{0,2}:{0,1}\d{0,2}:{0,1}\d{0,2}){0,1}\.{0,1}(\d{0,9})([\sZ]{0,1})([\+-]{0,1})([:\d]*)`
  44. // Regular expression2(datetime separator supports '-', '/', '.').
  45. // Eg:
  46. // 01-Nov-2018 11:50:28
  47. // 01/Nov/2018 11:50:28
  48. // 01.Nov.2018 11:50:28
  49. // 01.Nov.2018:11:50:28
  50. timeRegexPattern2 = `(\d{1,2}[-/\.][A-Za-z]{3,}[-/\.]\d{4})[:\sT-]*(\d{0,2}:{0,1}\d{0,2}:{0,1}\d{0,2}){0,1}\.{0,1}(\d{0,9})([\sZ]{0,1})([\+-]{0,1})([:\d]*)`
  51. // Regular expression3(time).
  52. // Eg:
  53. // 11:50:28
  54. // 11:50:28.897
  55. timeRegexPattern3 = `(\d{2}):(\d{2}):(\d{2})\.{0,1}(\d{0,9})`
  56. )
  57. var (
  58. // It's more high performance using regular expression
  59. // than time.ParseInLocation to parse the datetime string.
  60. timeRegex1, _ = regexp.Compile(timeRegexPattern1)
  61. timeRegex2, _ = regexp.Compile(timeRegexPattern2)
  62. timeRegex3, _ = regexp.Compile(timeRegexPattern3)
  63. // Month words to arabic numerals mapping.
  64. monthMap = map[string]int{
  65. "jan": 1,
  66. "feb": 2,
  67. "mar": 3,
  68. "apr": 4,
  69. "may": 5,
  70. "jun": 6,
  71. "jul": 7,
  72. "aug": 8,
  73. "sep": 9,
  74. "sept": 9,
  75. "oct": 10,
  76. "nov": 11,
  77. "dec": 12,
  78. "january": 1,
  79. "february": 2,
  80. "march": 3,
  81. "april": 4,
  82. "june": 6,
  83. "july": 7,
  84. "august": 8,
  85. "september": 9,
  86. "october": 10,
  87. "november": 11,
  88. "december": 12,
  89. }
  90. )
  91. // SetTimeZone sets the time zone for current whole process.
  92. // The parameter <zone> is an area string specifying corresponding time zone,
  93. // eg: Asia/Shanghai.
  94. //
  95. // This should be called before package "time" import.
  96. // Please refer to issue: https://github.com/golang/go/issues/34814
  97. func SetTimeZone(zone string) error {
  98. location, err := time.LoadLocation(zone)
  99. if err != nil {
  100. return err
  101. }
  102. return os.Setenv("TZ", location.String())
  103. }
  104. // Timestamp retrieves and returns the timestamp in seconds.
  105. func Timestamp() int64 {
  106. return Now().Timestamp()
  107. }
  108. // TimestampMilli retrieves and returns the timestamp in milliseconds.
  109. func TimestampMilli() int64 {
  110. return Now().TimestampMilli()
  111. }
  112. // TimestampMicro retrieves and returns the timestamp in microseconds.
  113. func TimestampMicro() int64 {
  114. return Now().TimestampMicro()
  115. }
  116. // TimestampNano retrieves and returns the timestamp in nanoseconds.
  117. func TimestampNano() int64 {
  118. return Now().TimestampNano()
  119. }
  120. // TimestampStr is a convenience method which retrieves and returns
  121. // the timestamp in seconds as string.
  122. func TimestampStr() string {
  123. return Now().TimestampStr()
  124. }
  125. // TimestampMilliStr is a convenience method which retrieves and returns
  126. // the timestamp in milliseconds as string.
  127. func TimestampMilliStr() string {
  128. return Now().TimestampMilliStr()
  129. }
  130. // TimestampMicroStr is a convenience method which retrieves and returns
  131. // the timestamp in microseconds as string.
  132. func TimestampMicroStr() string {
  133. return Now().TimestampMicroStr()
  134. }
  135. // TimestampNanoStr is a convenience method which retrieves and returns
  136. // the timestamp in nanoseconds as string.
  137. func TimestampNanoStr() string {
  138. return Now().TimestampNanoStr()
  139. }
  140. // Second returns the timestamp in seconds.
  141. // Deprecated, use Timestamp instead.
  142. func Second() int64 {
  143. return Timestamp()
  144. }
  145. // Millisecond returns the timestamp in milliseconds.
  146. // Deprecated, use TimestampMilli instead.
  147. func Millisecond() int64 {
  148. return TimestampMilli()
  149. }
  150. // Microsecond returns the timestamp in microseconds.
  151. // Deprecated, use TimestampMicro instead.
  152. func Microsecond() int64 {
  153. return TimestampMicro()
  154. }
  155. // Nanosecond returns the timestamp in nanoseconds.
  156. // Deprecated, use TimestampNano instead.
  157. func Nanosecond() int64 {
  158. return TimestampNano()
  159. }
  160. // Date returns current date in string like "2006-01-02".
  161. func Date() string {
  162. return time.Now().Format("2006-01-02")
  163. }
  164. // Datetime returns current datetime in string like "2006-01-02 15:04:05".
  165. func Datetime() string {
  166. return time.Now().Format("2006-01-02 15:04:05")
  167. }
  168. // ISO8601 returns current datetime in ISO8601 format like "2006-01-02T15:04:05-07:00".
  169. func ISO8601() string {
  170. return time.Now().Format("2006-01-02T15:04:05-07:00")
  171. }
  172. // ISO8601 returns current datetime in RFC822 format like "Mon, 02 Jan 06 15:04 MST".
  173. func RFC822() string {
  174. return time.Now().Format("Mon, 02 Jan 06 15:04 MST")
  175. }
  176. // parseDateStr parses the string to year, month and day numbers.
  177. func parseDateStr(s string) (year, month, day int) {
  178. array := strings.Split(s, "-")
  179. if len(array) < 3 {
  180. array = strings.Split(s, "/")
  181. }
  182. if len(array) < 3 {
  183. array = strings.Split(s, ".")
  184. }
  185. // Parsing failed.
  186. if len(array) < 3 {
  187. return
  188. }
  189. // Checking the year in head or tail.
  190. if utils.IsNumeric(array[1]) {
  191. year, _ = strconv.Atoi(array[0])
  192. month, _ = strconv.Atoi(array[1])
  193. day, _ = strconv.Atoi(array[2])
  194. } else {
  195. if v, ok := monthMap[strings.ToLower(array[1])]; ok {
  196. month = v
  197. } else {
  198. return
  199. }
  200. year, _ = strconv.Atoi(array[2])
  201. day, _ = strconv.Atoi(array[0])
  202. }
  203. return
  204. }
  205. // StrToTime converts string to *Time object. It also supports timestamp string.
  206. // The parameter <format> is unnecessary, which specifies the format for converting like "Y-m-d H:i:s".
  207. // If <format> is given, it acts as same as function StrToTimeFormat.
  208. // If <format> is not given, it converts string as a "standard" datetime string.
  209. // Note that, it fails and returns error if there's no date string in <str>.
  210. func StrToTime(str string, format ...string) (*Time, error) {
  211. if len(format) > 0 {
  212. return StrToTimeFormat(str, format[0])
  213. }
  214. if isTimestampStr(str) {
  215. timestamp, _ := strconv.ParseInt(str, 10, 64)
  216. return NewFromTimeStamp(timestamp), nil
  217. }
  218. var (
  219. year, month, day int
  220. hour, min, sec, nsec int
  221. match []string
  222. local = time.Local
  223. )
  224. if match = timeRegex1.FindStringSubmatch(str); len(match) > 0 && match[1] != "" {
  225. //for k, v := range match {
  226. // match[k] = strings.TrimSpace(v)
  227. //}
  228. year, month, day = parseDateStr(match[1])
  229. } else if match = timeRegex2.FindStringSubmatch(str); len(match) > 0 && match[1] != "" {
  230. //for k, v := range match {
  231. // match[k] = strings.TrimSpace(v)
  232. //}
  233. year, month, day = parseDateStr(match[1])
  234. } else if match = timeRegex3.FindStringSubmatch(str); len(match) > 0 && match[1] != "" {
  235. //for k, v := range match {
  236. // match[k] = strings.TrimSpace(v)
  237. //}
  238. s := strings.Replace(match[2], ":", "", -1)
  239. if len(s) < 6 {
  240. s += strings.Repeat("0", 6-len(s))
  241. }
  242. hour, _ = strconv.Atoi(match[1])
  243. min, _ = strconv.Atoi(match[2])
  244. sec, _ = strconv.Atoi(match[3])
  245. nsec, _ = strconv.Atoi(match[4])
  246. for i := 0; i < 9-len(match[4]); i++ {
  247. nsec *= 10
  248. }
  249. return NewFromTime(time.Date(0, time.Month(1), 1, hour, min, sec, nsec, local)), nil
  250. } else {
  251. return nil, gerror.New("unsupported time format")
  252. }
  253. // Time
  254. if len(match[2]) > 0 {
  255. s := strings.Replace(match[2], ":", "", -1)
  256. if len(s) < 6 {
  257. s += strings.Repeat("0", 6-len(s))
  258. }
  259. hour, _ = strconv.Atoi(s[0:2])
  260. min, _ = strconv.Atoi(s[2:4])
  261. sec, _ = strconv.Atoi(s[4:6])
  262. }
  263. // Nanoseconds, check and perform bit filling
  264. if len(match[3]) > 0 {
  265. nsec, _ = strconv.Atoi(match[3])
  266. for i := 0; i < 9-len(match[3]); i++ {
  267. nsec *= 10
  268. }
  269. }
  270. // If there's zone information in the string,
  271. // it then performs time zone conversion, which converts the time zone to UTC.
  272. if match[4] != "" && match[6] == "" {
  273. match[6] = "000000"
  274. }
  275. // If there's offset in the string, it then firstly processes the offset.
  276. if match[6] != "" {
  277. zone := strings.Replace(match[6], ":", "", -1)
  278. zone = strings.TrimLeft(zone, "+-")
  279. if len(zone) <= 6 {
  280. zone += strings.Repeat("0", 6-len(zone))
  281. h, _ := strconv.Atoi(zone[0:2])
  282. m, _ := strconv.Atoi(zone[2:4])
  283. s, _ := strconv.Atoi(zone[4:6])
  284. if h > 24 || m > 59 || s > 59 {
  285. return nil, gerror.Newf("invalid zone string: %s", match[6])
  286. }
  287. // Comparing the given time zone whether equals to current time zone,
  288. // it converts it to UTC if they does not equal.
  289. _, localOffset := time.Now().Zone()
  290. // Comparing in seconds.
  291. if (h*3600 + m*60 + s) != localOffset {
  292. local = time.UTC
  293. // UTC conversion.
  294. operation := match[5]
  295. if operation != "+" && operation != "-" {
  296. operation = "-"
  297. }
  298. switch operation {
  299. case "+":
  300. if h > 0 {
  301. hour -= h
  302. }
  303. if m > 0 {
  304. min -= m
  305. }
  306. if s > 0 {
  307. sec -= s
  308. }
  309. case "-":
  310. if h > 0 {
  311. hour += h
  312. }
  313. if m > 0 {
  314. min += m
  315. }
  316. if s > 0 {
  317. sec += s
  318. }
  319. }
  320. }
  321. }
  322. }
  323. if month <= 0 || day <= 0 {
  324. return nil, gerror.New("invalid time string:" + str)
  325. }
  326. return NewFromTime(time.Date(year, time.Month(month), day, hour, min, sec, nsec, local)), nil
  327. }
  328. // ConvertZone converts time in string <strTime> from <fromZone> to <toZone>.
  329. // The parameter <fromZone> is unnecessary, it is current time zone in default.
  330. func ConvertZone(strTime string, toZone string, fromZone ...string) (*Time, error) {
  331. t, err := StrToTime(strTime)
  332. if err != nil {
  333. return nil, err
  334. }
  335. if len(fromZone) > 0 {
  336. if l, err := time.LoadLocation(fromZone[0]); err != nil {
  337. return nil, err
  338. } else {
  339. t.Time = time.Date(t.Year(), time.Month(t.Month()), t.Day(), t.Hour(), t.Minute(), t.Time.Second(), t.Time.Nanosecond(), l)
  340. }
  341. }
  342. if l, err := time.LoadLocation(toZone); err != nil {
  343. return nil, err
  344. } else {
  345. return t.ToLocation(l), nil
  346. }
  347. }
  348. // StrToTimeFormat parses string <str> to *Time object with given format <format>.
  349. // The parameter <format> is like "Y-m-d H:i:s".
  350. func StrToTimeFormat(str string, format string) (*Time, error) {
  351. return StrToTimeLayout(str, formatToStdLayout(format))
  352. }
  353. // StrToTimeLayout parses string <str> to *Time object with given format <layout>.
  354. // The parameter <layout> is in stdlib format like "2006-01-02 15:04:05".
  355. func StrToTimeLayout(str string, layout string) (*Time, error) {
  356. if t, err := time.ParseInLocation(layout, str, time.Local); err == nil {
  357. return NewFromTime(t), nil
  358. } else {
  359. return nil, err
  360. }
  361. }
  362. // ParseTimeFromContent retrieves time information for content string, it then parses and returns it
  363. // as *Time object.
  364. // It returns the first time information if there're more than one time string in the content.
  365. // It only retrieves and parses the time information with given <format> if it's passed.
  366. func ParseTimeFromContent(content string, format ...string) *Time {
  367. if len(format) > 0 {
  368. if match, err := gregex.MatchString(formatToRegexPattern(format[0]), content); err == nil && len(match) > 0 {
  369. return NewFromStrFormat(match[0], format[0])
  370. }
  371. } else {
  372. if match := timeRegex1.FindStringSubmatch(content); len(match) >= 1 {
  373. return NewFromStr(strings.Trim(match[0], "./_- \n\r"))
  374. } else if match := timeRegex2.FindStringSubmatch(content); len(match) >= 1 {
  375. return NewFromStr(strings.Trim(match[0], "./_- \n\r"))
  376. } else if match := timeRegex3.FindStringSubmatch(content); len(match) >= 1 {
  377. return NewFromStr(strings.Trim(match[0], "./_- \n\r"))
  378. }
  379. }
  380. return nil
  381. }
  382. // ParseDuration parses a duration string.
  383. // A duration string is a possibly signed sequence of
  384. // decimal numbers, each with optional fraction and a unit suffix,
  385. // such as "300ms", "-1.5h", "1d" or "2h45m".
  386. // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h", "d".
  387. //
  388. // Very note that it supports unit "d" more than function time.ParseDuration.
  389. func ParseDuration(s string) (time.Duration, error) {
  390. if utils.IsNumeric(s) {
  391. v, err := strconv.ParseInt(s, 10, 64)
  392. if err != nil {
  393. return 0, err
  394. }
  395. return time.Duration(v), nil
  396. }
  397. match, err := gregex.MatchString(`^([\-\d]+)[dD](.*)$`, s)
  398. if err != nil {
  399. return 0, err
  400. }
  401. if len(match) == 3 {
  402. v, err := strconv.ParseInt(match[1], 10, 64)
  403. if err != nil {
  404. return 0, err
  405. }
  406. return time.ParseDuration(fmt.Sprintf(`%dh%s`, v*24, match[2]))
  407. }
  408. return time.ParseDuration(s)
  409. }
  410. // FuncCost calculates the cost time of function <f> in nanoseconds.
  411. func FuncCost(f func()) int64 {
  412. t := TimestampNano()
  413. f()
  414. return TimestampNano() - t
  415. }
  416. // isTimestampStr checks and returns whether given string a timestamp string.
  417. func isTimestampStr(s string) bool {
  418. length := len(s)
  419. if length == 0 {
  420. return false
  421. }
  422. for i := 0; i < len(s); i++ {
  423. if s[i] < '0' || s[i] > '9' {
  424. return false
  425. }
  426. }
  427. return true
  428. }