gtime.go 13 KB

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