gconv_time.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 gconv
  7. import (
  8. "time"
  9. "github.com/gogf/gf/internal/utils"
  10. "github.com/gogf/gf/os/gtime"
  11. )
  12. // Time converts <i> to time.Time.
  13. func Time(i interface{}, format ...string) time.Time {
  14. // It's already this type.
  15. if len(format) == 0 {
  16. if v, ok := i.(time.Time); ok {
  17. return v
  18. }
  19. }
  20. if t := GTime(i, format...); t != nil {
  21. return t.Time
  22. }
  23. return time.Time{}
  24. }
  25. // Duration converts <i> to time.Duration.
  26. // If <i> is string, then it uses time.ParseDuration to convert it.
  27. // If <i> is numeric, then it converts <i> as nanoseconds.
  28. func Duration(i interface{}) time.Duration {
  29. // It's already this type.
  30. if v, ok := i.(time.Duration); ok {
  31. return v
  32. }
  33. s := String(i)
  34. if !utils.IsNumeric(s) {
  35. d, _ := gtime.ParseDuration(s)
  36. return d
  37. }
  38. return time.Duration(Int64(i))
  39. }
  40. // GTime converts <i> to *gtime.Time.
  41. // The parameter <format> can be used to specify the format of <i>.
  42. // If no <format> given, it converts <i> using gtime.NewFromTimeStamp if <i> is numeric,
  43. // or using gtime.StrToTime if <i> is string.
  44. func GTime(i interface{}, format ...string) *gtime.Time {
  45. if i == nil {
  46. return nil
  47. }
  48. // It's already this type.
  49. if len(format) == 0 {
  50. if v, ok := i.(*gtime.Time); ok {
  51. return v
  52. }
  53. }
  54. s := String(i)
  55. if len(s) == 0 {
  56. return gtime.New()
  57. }
  58. // Priority conversion using given format.
  59. if len(format) > 0 {
  60. t, _ := gtime.StrToTimeFormat(s, format[0])
  61. return t
  62. }
  63. if utils.IsNumeric(s) {
  64. return gtime.NewFromTimeStamp(Int64(s))
  65. } else {
  66. t, _ := gtime.StrToTime(s)
  67. return t
  68. }
  69. }